0

我已经实现了一个扩展 MediaPlayer 的类。

public class AudioPlayer extends MediaPlayer {
   private String fileName = null;
   FileInputStream fileInputStream = null;  
   private MediaPlayer mediaPlayer = null;

   // Constructor
   public AudioPlayer(Context context) 
   {    
    // Initialization
   }

   public void onPlay(boolean start)
   {
       if(start) {
        startPlaying(this.fileName);
       }else {
        stopPlaying(this.fileName);
       }
   }

   private void startPlaying(String fileName) {
       mediaPlayer = new MediaPlayer();
       mediaPlayer.setDataSource(fileInputStream.getFD());
       mediaPlayer.prepare();
       mediaPlayer.start();

    // mediaPlayer.setOnCompletionListener(new CompletionListener());
    }

class CompletionListener implements MediaPlayer.OnCompletionListener {
    @Override
    public void onCompletion(MediaPlayer mp) {

        // Do stuff
        }        
    }

当我在自定义 AudioPlayer 类中的 MediaPlayer 对象上 setOnCompletionListener 时,它工作得很好。但是,我想在从此类创建的对象上设置此侦听器,因为它用于多个活动。在 onCompletion() 方法中应该采取不同的操作,因此在我的自定义类中实现 onCompletionListener 是没有意义的。当我在要使用它的每个活动中创建自定义类的实例时

AudioPlayer audioPlayer = new AudioPlayer(context);

并在其上设置 onCompletionListener:

audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO Auto-generated method stub

        }
    });

它永远不会被调用。有没有办法在我的自定义对象上调用 onCompletionListener?

4

1 回答 1

0

The solution is to write a method that returns MediaPlayer object and then call setOnCompletionListener() on this object:

public MediaPlayer getActiveMediaPlayer()
{
    if ( mediaPlayer != null )
        return this.mediaPlayer;
    else 
        return null;
}

and then in the activity:

audioRecorder.getActiveMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.d("MediaPlayer", "test");

        }
    });
于 2012-10-24T00:08:14.077 回答