seekBar.setMax(mp.getDuration())返回0

时间:2013-07-15 10:03:09

标签: android android-mediaplayer

我正在开发MediaPlayer。播放器工作正常,音乐正在流式播放,但我在设置搜索栏时遇到了麻烦。我假设搜索栏与通过getDuration获得正确的持续时间直接相关,然后我们继续前进。

基本上,我正在关注此tutorial,如果数据源是网址而不是本地文件,请尝试修改它。

以下是我设置mediaPlayer对象并尝试getDuration

的方法
Uri uri = Uri.parse(sURL);
System.out.println(uri);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(this, uri); 
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {  
     @Override  
     public void onPrepared(MediaPlayer mp) {  
         seekBar.setMax(mp.getDuration());
         System.out.println("Duration of file is = " + mp.getDuration());
     }  
});
initViews(mediaPlayer);

MediaPlayer对象是在onCreate中启动的。这些是处理搜索栏和进度跟踪的其他方法。

// This method set the setOnClickListener and method for it (buttonClick())
private void initViews(MediaPlayer mediaPlayer) {
    Log.i("Main", "initViews");
    buttonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
    buttonPlayStop.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {buttonClick();}});

    seekBar = (SeekBar) findViewById(R.id.SeekBar01);       
    //Log.i ("info", String.valueOf(mediaPlayer.getDuration()));
    seekBar.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {
        seekChange(v);
        return false; }
    });

}

public void startPlayProgressUpdater() {
    seekBar.setProgress(mediaPlayer.getCurrentPosition());

    if (mediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                startPlayProgressUpdater();
            }
        };
        handler.postDelayed(notification,1000);
    }else{
        mediaPlayer.pause();
        buttonPlayStop.setText(getString(R.string.play_str));
        seekBar.setProgress(0);
    }
} 

// This is event handler thumb moving event
private void seekChange(View v){
    if(mediaPlayer.isPlaying()){
        SeekBar sb = (SeekBar)v;
        mediaPlayer.seekTo(sb.getProgress());
    }
}

// This is event handler for buttonClick event
private void buttonClick(){
    if (buttonPlayStop.getText() == getString(R.string.play_str)) {
        buttonPlayStop.setText(getString(R.string.pause_str));
        try{
            mediaPlayer.start();
            startPlayProgressUpdater(); 
        }catch (IllegalStateException e) {
            mediaPlayer.pause();
        }
    }else {
        buttonPlayStop.setText(getString(R.string.play_str));
        mediaPlayer.pause();
    }
}

有人可以在这方面指导我吗?

0 个答案:

没有答案