Sound only plays in debug mode

Asked

Viewed 68 times

5

Because the sound only plays in debug mode?

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.start();
mp.reset();
mp.release();

2 answers

4

The "play" of a sound by Mediaplayer is initiated by the method call mp.start(). However the sound is "played" asynchronously, that is, after called, the method mp.start() returns immediately.

Thus the next instruction(mp.reset()) is immediately performed, causing the sound to be finished.

The reason you can hear the sound in debug, I suppose that in step by step, is because the execution of the program is slower, making it spend more time between the execution of mp.start() and mp.reset().

To see how you should use Mediaplayer see How to play a sound using Mediaplayer.

  • thank you very much, the example worked perfectly!

2

Ultraseven,

You’re making some mistakes. I’m going to begin the explanation with an image I took from Mediaplayer class documentation

inserir a descrição da imagem aqui

Notice what the reset method and method release() do, or to what state they lead the MediaPlayer. After executing the method reset() the MediaPlayer goes to the state Idle or idle and, after executing the method release(), goes to the state of end or finalised/closed.

What happens is that after running the audio with the method start(), soon after you run the method reset() leaving the MediaPlayer idle, and the method release(), ending the MediaPlayer. That is, the audio starts to be executed and then is paused for getting idle and finished.

I believe the confusion you’re making is because you believe the method reset() and release() will only be executed when the audio has finished playing on start(), that is, that the method start() is stuck until the audio ends. But that’s not how it works, the start() is asynchronous, that is, its execution will happen in parallel to the other lines below.

I hope I’ve been clear, anything leave a comment.

  • Your clarification together with the @ramaral tip were perfect. Thank you.

  • Good morning, I passed the code to another class and it’s giving context error in create. I’ve been through this problem in the past but this context business I still can’t understand. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.