0

我正在开发 MediaPlayer。播放器工作正常,音乐流式传输正常,但我无法将搜索栏设置为工作。我假设 seekbar 与通过 getDuration 获得正确的持续时间直接相关,然后我们继续前进。

基本上,如果数据源是 url 而不是本地文件,我正在关注本教程并尝试修改它以使其工作。

这是我设置 mediaPlayer 对象并尝试获取持续时间的方式

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();
    }
}

谁能在这方面指导我?

4

0 回答 0