停止的MediaPlayer当其他应用程序播放音乐 [英] Stop MediaPlayer when an other app play music
问题描述
在我的应用程序,我有一个媒体播放器,播放流音乐:
In my app, I have a media player which play a stream music:
globalVariable.setPlaying(true);
final ProgressDialog mProgressDialog;
mProgressDialog = ProgressDialog.show(MainActivity.this, "Chargement en cours", "La musique est en train de charger", true);
String url = "http://178.32.181.86:18000";
globalVariable.mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
globalVariable.mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
globalVariable.mp.prepareAsync();
globalVariable.mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
bouton.setImageResource(R.drawable.pause);
mProgressDialog.hide();
}
});
它工作得很好。当我在我面前打开另一个应用程序,玩家继续,它的伟大。但是,如果我发动另一名球员(如GooglePlayMusic或YouTube),我的应用程序不会停止音乐,我有两个声音在同一时间。
It works very fine. When I open another app in front of mine, player continues, and it's great. But if I launch another player (like GooglePlayMusic or youtube), my app doesn't stop music and I have two sounds in the same time.
所以,我想,如果另一个应用程序需要播放的音乐我的音乐停下来。
So I want that my music stop if another app need to play music.
非常感谢
推荐答案
您应该使用AudioManager服务是否接收到接收通知/音频丢失焦点(的管理音频焦点)。我在一个项目中,当我的应用程序开始播放,谷歌播放暂停,反之亦然做过类似的事情。使用以下code你在哪里控制你的媒体播放像(活动或服务) -
You should use AudioManager service to receive notification whether you receive/lost audio focus (Managing audio focus). I've done similar thing in a project where when my app starts playing, Google Play pause and vice versa. Use the following code where you are controlling your media playback like (activity or service)-
// Add this code in a method
AudioManager am = null;
// Request focus for music stream and pass AudioManager.OnAudioFocusChangeListener
// implementation reference
int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
// Play
}
// Implements AudioManager.OnAudioFocusChangeListener
@Override
public void onAudioFocusChange(int focusChange)
{
if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
{
// Pause
}
else if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
{
// Resume
}
else if(focusChange == AudioManager.AUDIOFOCUS_LOSS)
{
// Stop or pause depending on your need
}
}
这篇关于停止的MediaPlayer当其他应用程序播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!