音频没有播放

时间:2014-02-22 20:11:38

标签: android media-player android-mediaplayer

我试图创建一个扩展Mediaplayer的类,当我播放声音时,我想在调用声音的活动中触发事件处理程序。

我的活动:

SoundPlayer soundPlayer = new SoundPlayer(BookInterface.this);
soundPlayer.playSound(this, R.raw.vroom);

这是SoundPlayer类:

public class SoundPlayer extends MediaPlayer{

    BookInterface ownerActivity;

    public SoundPlayer(BookInterface act){
        ownerActivity = act;
    }

    public void playSound(Context context, int resId){
        Log.d("Debug", "playSound is called");
        MediaPlayer mp = new MediaPlayer();
        try {
            mp = MediaPlayer.create(context, resId);
            mp.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("Debug","Exception" + e);
            e.printStackTrace();
        }

        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("Debug", "playSound.onCompletion is called");
                mp.stop();
                mp.release();
                ownerActivity.eventHandler();
            }
        });     
    }
}

为什么不播放声音? 我做错了什么?

BR

1 个答案:

答案 0 :(得分:0)

为什么要在MediaPlayer方法内声明playSound? 我认为当playSound方法执行完成后,MediaPlayer从内存中清除,尝试将MediaPlayer声明为类变量,如下所示:

public class SoundPlayer extends MediaPlayer{

    BookInterface ownerActivity;
    private MediaPlayer mp;

    public SoundPlayer(BookInterface act){
        ownerActivity = act;
    }

    public void playSound(Context context, int resId){
        Log.d("Debug", "playSound is called");
        try {
            mp = MediaPlayer.create(context, resId);

            mp.setOnCompletionListener(new OnCompletionListener() {

              @Override
              public void onCompletion(MediaPlayer mp) {
                  Log.d("Debug", "playSound.onCompletion is called");
                  mp.stop();
                  mp.release();
                  ownerActivity.eventHandler();
              }
            });

            mp.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("Debug","Exception" + e);
            e.printStackTrace();
        }     
    }
}