Pergunta

I've a problem with seek bar, when i play the audio with mediaplayer the seekbar don't start with it. i don't understand why the seekbar don't "refresh" progress.

thank you for help.

below i post the code, i don't understand when i wrong.

MediaPlayer  player=new MediaPlayer();
SeekBar seekBar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.mymp3);
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        player.prepare();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Button pausa=(Button)findViewById(R.id.button2);  
    pausa.setOnClickListener(new OnClickListener(){  
                @Override  
                public void onClick(View arg0) { 
                    player.pause();
                }  
            }); 
   Button vai=(Button)findViewById(R.id.button3);  
    vai.setOnClickListener(new OnClickListener(){  
                @Override  
                public void onClick(View arg0) {
                    player.start();
                }  
            });

    int tutto=player.getDuration();

    seekBar = (SeekBar)findViewById(R.id.seekBar1);

    seekBar.setMax(tutto);
    seekBar.setProgress(player.getCurrentPosition() / 1000);
}
Foi útil?

Solução

An easy way you can do it is to create a Timer object that fires every second.

Inside the code of the timer you call

seekBar.setProgress(player.getCurrentPosition() / 1000);

Additionally, you may want to implement setOnCompletionListener to get notified when the playback has reached it's end so you can stop the timer. The timer should be stopped either if the playback reached it's end, the applications finishes, or you stop the music manually (in response to a stop button, for example)

Outras dicas

Because you set the progress in onCreate() and that gets called only once - you guessed it, when the Activity is created. I'm not very familiar with the MediaPlayer so I don't know if there is some kind of update listener, but you need some kind of timer that updates the progress every second or so.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top