質問

I want to play a sound when onPause() of my Activity is called. To do so, I use the following code:

@Override
public void onPause()
{
    super.onPause();

    MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
    player.setLooping(false);
    player.start();
}

This works fine, but the sound keeps on playing forever. I tried adding an OnCompletionListener, but that didn't help (the Listener is never called).

I know that I'm not calling player.stop() and player.release() anywhere, but I wouldn't even know where to do so.

My question is now: How can I make the sound play only once? Is there a way to wait for the media player to finish before the application goes to the background?

役に立ちましたか?

解決

Ok, I found the solution.

The problem was, that I was using Settings.System.DEFAULT_RINGTONE_URI, which apparently never stops playing.

Using Settings.System.DEFAULT_NOTIFICATION_URI instead fixed the issue.

他のヒント

You can try this (if I've understood correctly)

public boolean test=false; // At begin

public void onPause()
{
    super.onPause();
if(!test){
    MediaPlayer player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
    player.setLooping(false);
    player.start();
    test=true;
}
}

Maybe I don't understand what you want to say. If you explain us a little bit more, maybe we can help to you :)

I haven't done this,, but I think you can check this one

       player.setLooping(false);
       player.setOnCompletionListener(new OnCompletionListener() 
        {
            @Override
            public void onCompletion(MediaPlayer mp)
            {
                player.stop();
                player.release();
            }
        });

Not sure why it plays in loop but you can you use MediaElement to play sound? You can identify when media is ended by using method MediaEnded and then call stop method to stop playing audio

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top