如何在没有音频的情况下播放视频,并且不会中断背景音乐?也就是说,音乐应用或Soundcloud等后台应用播放的音频不应该停止播放。
如果您查看Facebook应用,则自动播放视频功能不会中断/停止背景音乐。我想在我的应用程序中使用类似的行为。
答案 0 :(得分:0)
在视频视图中尝试setAudioFocusRequest(AUDIOFOCUS_NONE)
答案 1 :(得分:0)
如果您使用的是ExoPlayer,则可以执行以下操作:
SimpleExoPlayer simpleExoPlayer = new SimpleExoPlayer.Builder(this).build();
// just add below line to stop background music
simpleExoPlayer.setAudioAttributes(simpleExoPlayer.getAudioAttributes(), /*
handleAudioFocus= */ true);
答案 2 :(得分:0)
以下代码可以正常工作
private void gainFocus( AudioManager.OnAudioFocusChangeListener focusChangeListener){
AudioManager am = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
}
并在活动的onCreate()方法中注册音频焦点的侦听器,然后根据音频焦点的条件状态调用gainfocus()方法
void registerAudioFocus(){
if(mMediaPlayer!=null){
/*code for stop other application sound while app video playing*/
focusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
if(mMediaPlayer!=null)
mMediaPlayer.setVolume(0.2f, 0.2f);
//Toast.makeText(getContext(),"AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK",Toast.LENGTH_LONG).show();
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
pause();
// Toast.makeText(getContext(),"AUDIOFOCUS_LOSS_TRANSIENT",Toast.LENGTH_LONG).show();
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
if(mMediaPlayerValid) {
gainFocus(this);
}
else
{
((AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(focusChangeListener);
}
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
// Toast.makeText(getContext(),"AUDIOFOCUS_GAIN",Toast.LENGTH_LONG).show();
if(mMediaPlayer!=null) {
mMediaPlayer.setVolume(1f, 1f);
mMediaPlayer.start();
}
gainFocus(this);
break;
default: break;
}
}
};
gainFocus(focusChangeListener);
}
}
请这个对我来说很好
答案 3 :(得分:-1)
我猜您正在使用VideoView来显示视频。尝试使用SurfaceView。我已经尝试了两种,事实上VideoView会停止任何第三方音乐应用,而SurfaceView则不会。