我可以将onCompletionListener()设置为一个对象,该对象是扩展MediaPlayer的类的实例吗?

时间:2012-10-23 21:40:56

标签: android android-mediaplayer

我实现了一个扩展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?

1 个答案:

答案 0 :(得分:0)

解决方案是编写一个返回MediaPlayer对象的方法,然后在该对象上调用setOnCompletionListener():

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

然后在活动中:

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

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

        }
    });