Android studio mediaplayer seekbar

Android — SeekBar и MediaPlayer

Мне нужно было соединить мой SeekBar с моим MediaPlayer в моем приложении.

Я настроил SeekBar через xml следующим образом:

И следовал этому SO ответу, чтобы реализовать его.

Процесс начинается с метода onOptionsItemSelected .

seekBar работает правильно, он увеличивается каждую секунду. Проблема в том, что он заканчивает путь раньше, чем заканчивается песня.

Я пытался добавить

В методе setup , но это заставляет планку вообще не двигаться.

3 ответа

Вам нужно определить отдельный Runnable и запускать его каждые x миллисекунд (зависит от вас) после запуска MediaPlayer .

Определить функцию updateSeekbar как,

Теперь вам просто нужно позвонить updateSeekbar один раз, когда начнется игра. В твоем случае:

Функция milliSecondsToTimer работает следующим образом

Вы позвонили setMax не в том месте. Обновите функцию setup() следующим образом

Вам нужно обновить панель поиска, когда вы играете песню

Ниже Runnable метод для обновления seekbar

Используя эту функцию ниже, вы можете получить процент прогресса от текущей позиции песни и длительности песни

Вы реализовали OnSeekBarChangeListener и в onCreate() добавили следующую строку: —

И переопределите метод onProgressChanged() , в этом методе вы можете установить прогресс в строке поиска, используя следующую строку:

После того, как вы инициализируете свой MediaPlayer и, например, нажимаете кнопку воспроизведения, вы должны создать обработчик и опубликовать исполняемый файл, чтобы вы могли обновить свой SeekBar (в самом потоке пользовательского интерфейса) с текущей позицией вашего MediaPlayer, например так:

И обновлять это значение каждую секунду.

Если вам нужно обновить позицию MediaPlayer, когда пользователь перетаскивает ваш SeekBar, вы должны добавить OnSeekBarChangeListener в свой SeekBar и сделать это там:

Источник

SeekBar и медиаплеер в android

У меня есть простой плеер и рекордер. Все работает отлично, но есть одна проблема. Я хочу добавить панель поиска, чтобы увидеть прогресс в воспроизведении записи и использовать эту панель поиска, чтобы установить место от игрока. У меня есть onProgress, но без эффекта. Это код:

любые идеи, как использовать панель поиска, чтобы увидеть прогресс и установить место из записи, должны играть?

11 ответов

создать связь между SeekBar и MediaPlayer сначала вам нужно получить текущую максимальную продолжительность записи и установить ее на панель поиска.

после инициализации вашего MediaPlayer и, например, нажмите кнопку воспроизведения, вы должны создать обработчик и опубликовать runnable, чтобы вы могли обновить свой SeekBar (в UI thread сам) с текущей позицией вашего MediaPlayer такой :

и обновляйте это значение каждую секунду.

если вам необходимо обновить MediaPlayer ‘s позиция в то время как пользователь перетащить SeekBar вы должны добавить OnSeekBarChangeListener на SeekBar и здесь :

и это должно сделать трюк! : )

EDIT: Одна вещь, которую я заметил в вашем коде, не надо :

сделать все initialisations в onCreate(); , не создавайте конструкторы вашего Activity .

после инициализации MediaPlayer и SeekBar , вы можете сделать это :

обновления SeekBar каждую секунду (1000ms)

и для обновления MediaPlayer , если пользователь перетаскивает SeekBar , вы должны добавить OnSeekBarChangeListener на SeekBar :

проверьте это, вы должны дать аргументы в msecs, не просто отправить progress до seekTo (int)

вы можете сделать некоторые вычисления, т. е. преобразуйте progress в msec как msce = (progress/100)*getDuration() затем сделать seekTo(msec)

или еще у меня есть простая идея, вам не нужно менять какой-либо код anywer, просто добавьте seekBar.setMax(mPlayer.getDuration()) как только ваш медиаплеер будет готов.

и вот ссылка именно то, что вы хотите обновление панели поиска

после MediaPlayer Я.е mplayer.start()

попробуйте этот код

прежде чем добавить этот код, вы должны создать xml ресурс SeekBar и используйте его в своем Activity класс ur onCreate() метод.

чтобы добавить к ответу @hardartcore.

вместо вызова postDelayed на обработчике, лучшим подходом было бы получить обратные вызовы от MediaPlayer во время воспроизведения, а затем соответственно обновите панель поиска с прогрессом.

Читайте также:  Ubuntu не видит андроид

кроме того, приостановите MediaPlayer at onStartTrackingTouch(SeekBar seekBar) на OnSeekBarChangeListener а затем снова запустите его на onStopTrackingTouch(SeekBar seekBar) .

на основе предыдущих операторов для повышения производительности вы также можете добавить условие if

ниже код работал для меня.

Я создал метод для seekbar

SongProgress и SongMaxLength являются TextView, чтобы показать продолжительность песни и длину песни.

Источник

Android Media Player Song With SeekBar

Android Tutorial

In this tutorial, we’ll use the MediaPlayer class to implement a basic Audio Player in our Android Application. We’ll add a Play/Stop feature and also allow the user to change the position of the song with a SeekBar.

Android MediaPlayer

MediaPlayer class is used for playing Audio and Video files. The common methods of the MediaPlayer class that we’ll use are:

  • start()
  • stop()
  • release() – To prevent memory leaks.
  • seekTo(position) – This will be used with the SeekBar
  • isPlaying() – Let’s us know whether the song is being played or not.
  • getDuration() – Is used to get the total duration. Using this we’ll know the upper limit of our SeekBar. This function returns the duration in milli seconds
  • setDataSource(FileDescriptor fd) – This is used to set the file to be played.
  • setVolume(float leftVolume, float rightVolume) – This is used to set the volume level. The value is a float between 0 an 1.

We’ll be playing an mp3 file stored in the assets folder of our Android Studio Project.

Fetching the sound assets file from the Assets folder

In order to create an Application that plays Audio and lets you change the position of the current song track we need to implement three things:

  • MediaPlayer
  • SeekBar With Text – To show the current progress time besides the thumb.
  • Runnable Thread – To update the Seekbar.

Project Structure

Add the following dependency in your build.gradle:

The code for the activity_main.xml is given below:

We’ve added a FloatingActionButon that’ll play/stop when clicked.

The code for the MainActivity.java class is given below:

In the above code on clicking the FloatingActionButton, the playSong function gets triggered in which we stop the song and reset the MediaPlayer and FloatingActionButton icon every second time.

Once the mediaPlayer.prepare() is called, the details are available for the song. We can now get the duration and set it on the SeekBar max position.

setLoooping to false prevents the song from playing infinitely until stopped by the user.

We start the thread which triggers the run method which was a part of the Runnable interface that we’ve implemented.

Inside the run method, we update the progress every second which triggers the onProgressChanged method of the SeekBar listener.

Inside the listener, we’ve set the TextView offset to below the SeekBar’s thumb. We set the time duration by converting the milliseconds to seconds there.

When the seek bar is moved the same method is triggered. When the user stops scrubbing the SeekBar the onStopTrackingTouch is triggered in which using the seekTo method we update the song position on the MediaPlayer instance.

Once the song is completed, we update the position of the SeekBar back to the initial and clear the MediaPlayer instance.

The output of the application without audio is given below:

This brings an end to this tutorial. You can download the project from the link below and play the song for yourself.

Источник

Android Audio / Media Player with Examples

In android, by using MediaPlayer class we can easily fetch, decode and play both audio and video files with minimal setup.

The android media framework provides built-in support for playing a variety of common media types, such as audio or video. We have multiple ways to play audio or video but the most important component of media framework is MediaPlayer class.

Читайте также:  Icloud для айфона для андроида

Android MediaPlayer Class

In android, by using MediaPlayer class we can access audio or video files from application (raw) resources, standalone files in file system or from a data stream arriving over a network connection and play audio or video files with the multiple playback options such as play, pause, forward, backward, etc.

Following is the code snippet, to play an audio that is available in our application’s local raw resource (res/raw) directory.

The second parameter in create() method is the name of the song that we want to play from our application resource directory (res/raw). In case if raw folder not exists in your application, create a new raw folder under res directory and add a properly encoded and formatted media files in it.

In case, if we want to play an audio from a URI that is locally available in the system, we need to write the code like as shown below.

If we want to play an audio from a URL via HTTP streaming, we need to write the code like as shown below.

If you observe above code snippets, we create an instance of MediaPlayer class and added required audio source, streaming type, audio file path, etc. to play an audio from our application.

Apart from above methods, MediaPlayer class provides a different type of methods to control audio and video files based on requirements.

Method Description
getCurrentPosition() It is used to get the current position of the song in milliseconds.
getDuration() It is used to get the total time duration of the song in milliseconds.
isPlaying() It returns true / false to indicate whether song playing or not.
pause() It is used to pause the song playing.
setAudioStreamType() it is used to specify the audio streaming type.
setDataSource() It is used to specify the path of audio / video file to play.
setVolume() It is used to adjust media player volume either up / down.
seekTo(position) It is used to move song to particular position in milliseconds.
getTrackInfo() It returns an array of track information.
start() It is used to start playing the audio/video.
stop() It is used to stop playing the audio/video.
reset() It is used to reset the MediaPlayer object.
release() It is used to releases the resources which are associated with MediaPlayer object.

Now we will see how to implement media playing application using MediaPlayer to play a song or audio with multiple playback options, such as play, pause, forward, backward in android application with examples.

Android Audio Player Example

Following is the example of implementing an audio player to play a song or audio with multiple playback options using MediaPlayer.

Create a new android application using android studio and give names as MediaPlayerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

As discussed create a new raw folder in res directory and add one music file like as shown below to play it by using MediaPlayer class.

Now open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :paddingLeft= «10dp»
android :paddingRight= «10dp» >
TextView
android :id= «@+id/txtVw1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Now Playing: »
android :layout_marginTop= «30dp»
android :textAppearance= «?android:attr/textAppearanceMedium»/>
TextView
android :id= «@+id/txtSname»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_alignBaseline= «@+id/txtVw1»
android :layout_toRightOf= «@+id/txtVw1»
android :text= «TextView»/>
ImageView
android :id= «@+id/imgLogo»
android :layout_width= «match_parent»
android :layout_height= «450dp»
android :layout_below= «@+id/txtVw1»
android:src= «@drawable/tutlane»/>
ImageButton
android:id= «@+id/btnBackward»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_alignParentBottom= «true»
android:layout_marginBottom= «44dp»
android:layout_marginLeft= «20dp»
android:src= «@android:drawable/ic_media_rew»/>
ImageButton
android:id= «@+id/btnPlay»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_alignTop= «@+id/btnBackward»
android:layout_marginLeft= «20dp»
android:layout_toRightOf= «@+id/btnBackward»
android:src= «@android:drawable/ic_media_play»/>
ImageButton
android:id= «@+id/btnPause»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_alignTop= «@+id/btnPlay»
android:layout_marginLeft= «20dp»
android:layout_toRightOf= «@+id/btnPlay»
android:src= «@android:drawable/ic_media_pause»/>
ImageButton
android:id= «@+id/btnForward»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_alignTop= «@+id/btnPause»
android:layout_marginLeft= «20dp»
android :layout_toRightOf= «@+id/btnPause»
android :contentDescription= «@+id/imageButton3»
android:src= «@android:drawable/ic_media_ff»/>
TextView
android:id= «@+id/txtStartTime»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_alignTop= «@+id/sBar»
android:text= «0 min, 0 sec»/>
SeekBar
android:id= «@+id/sBar»
android:layout_width= «match_parent»
android:layout_height= «wrap_content»
android:layout_above= «@+id/btnBackward»
android:layout_toLeftOf= «@+id/txtSongTime»
android:layout_toRightOf= «@+id/txtStartTime»/>
TextView
android:id= «@+id/txtSongTime»
android:layout_width= «wrap_content»
android:layout_height= «wrap_content»
android:layout_toRightOf= «@+id/btnForward»
android:layout_alignTop= «@+id/sBar»
android:text= «0 min, 0 sec »/>
RelativeLayout >

Now open your main activity file MainActivity.java from \java\com.tutlane.audioplayerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.mediaplayerexample;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity <
private ImageButton forwardbtn , backwardbtn , pausebtn , playbtn ;
private MediaPlayer mPlayer ;
private TextView songName , startTime , songTime ;
private SeekBar songPrgs ;
private static int oTime = 0 , sTime = 0 , eTime = 0 , fTime = 5000 , bTime = 5000 ;
private Handler hdlr = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
backwardbtn = (ImageButton)findViewById(R.id. btnBackward );
forwardbtn = (ImageButton)findViewById(R.id. btnForward );
playbtn = (ImageButton)findViewById(R.id. btnPlay );
pausebtn = (ImageButton)findViewById(R.id. btnPause );
songName = (TextView)findViewById(R.id. txtSname );
startTime = (TextView)findViewById(R.id. txtStartTime );
songTime = (TextView)findViewById(R.id. txtSongTime );
songName .setText( «Baitikochi Chuste» );
mPlayer = MediaPlayer.create( this , R.raw. baitikochi_chuste );
songPrgs = (SeekBar)findViewById(R.id. sBar );
songPrgs .setClickable( false );
pausebtn .setEnabled( false );

playbtn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
Toast.makeText(MainActivity. this , «Playing Audio» , Toast. LENGTH_SHORT ).show();
mPlayer .start();
eTime = mPlayer .getDuration();
sTime = mPlayer .getCurrentPosition();
if ( oTime == 0 ) <
songPrgs .setMax( eTime );
oTime = 1 ;
>
songTime .setText(String.format( «%d min, %d sec» , TimeUnit. MILLISECONDS .toMinutes( eTime ),
TimeUnit. MILLISECONDS .toSeconds( eTime ) — TimeUnit. MINUTES .toSeconds(TimeUnit. MILLISECONDS . toMinutes( eTime ))) );
startTime .setText(String.format( «%d min, %d sec» , TimeUnit. MILLISECONDS .toMinutes( sTime ),
TimeUnit. MILLISECONDS .toSeconds( sTime ) — TimeUnit. MINUTES .toSeconds(TimeUnit. MILLISECONDS . toMinutes( sTime ))) );
songPrgs .setProgress( sTime );
hdlr .postDelayed( UpdateSongTime , 100 );
pausebtn .setEnabled( true );
playbtn .setEnabled( false );
>
>);
pausebtn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
mPlayer .pause();
pausebtn .setEnabled( false );
playbtn .setEnabled( true );
Toast.makeText(getApplicationContext(), «Pausing Audio» , Toast. LENGTH_SHORT ).show();
>
>);
forwardbtn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
if (( sTime + fTime ) eTime )
<
sTime = sTime + fTime ;
mPlayer .seekTo( sTime );
>
else
<
Toast.makeText(getApplicationContext(), «Cannot jump forward 5 seconds» , Toast. LENGTH_SHORT ).show();
>
if (! playbtn .isEnabled()) <
playbtn .setEnabled( true );
>
>
>);
backwardbtn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
if (( sTime — bTime ) > 0 )
<
sTime = sTime — bTime ;
mPlayer .seekTo( sTime );
>
else
<
Toast.makeText(getApplicationContext(), «Cannot jump backward 5 seconds» , Toast. LENGTH_SHORT ).show();
>
if (! playbtn .isEnabled()) <
playbtn .setEnabled( true );
>
>
>);
>
private Runnable UpdateSongTime = new Runnable() <
@Override
public void run() <
sTime = mPlayer .getCurrentPosition();
startTime .setText(String.format( «%d min, %d sec» , TimeUnit. MILLISECONDS .toMinutes( sTime ),
TimeUnit. MILLISECONDS .toSeconds( sTime ) — TimeUnit. MINUTES .toSeconds(TimeUnit. MILLISECONDS .toMinutes( sTime ))) );
songPrgs .setProgress( sTime );
hdlr .postDelayed( this , 100 );
>
>;
>

If you observe above code we used MeidaPlayer object properties to play, pause song and changing the song position either forward or backward based on our requirements.

Output of Android Audio Player Example

When we run the above program in the android studio we will get the result as shown below.

If you observe above result, when we click on play button song will start play and it will show the song duration details. If we click on pause button, the song will stop playing and use forward and backward buttons to move song forward or backward based on your requirements.

This is how we can implement audio player app in android applications with multiple playback options based on our requirements.

Источник

Читайте также:  Android service permission denied
Оцените статью