Domanda

I've tried to make a class that extends Mediaplayer and when I've played a sound I want to trigger an event handler in the activity calling the sound.

I Activity:

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

And this is the SoundPlayer class:

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

Why isnt the sound playing? What am I doing wrong?

BR

È stato utile?

Soluzione

Why you declare your MediaPlayer inside playSound method?
I think when playSound method execution is done your MediaPlayer cleared from memory, try to declare MediaPlayer as class variable like this:

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();
        }     
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top