[DESCRIPTION]
MT6735如何监听手机上面音乐/FM等多媒体声音的播放/停止的动作?
[SOLUTION]
android有一个AudioFocus的机制,要播放声音的app可以去requestAudioFocus(),当拿到audiofocus之后再播放音乐 ,当失去audiofocus的时候做停止播放的动作,当自己的播放动作结束后,释放audiofocus。通过audiofocus可以做到 监听有使用audiofocus的那些app的播放/停止的动作,可以达到在同一时间,只有拿到audiofocus的app才可以播放音 乐的目的,这样可以避免各个app的声音相互冲突。
代码例子如下:
1)要播放时,先requestAudioFocus(),再Startplayback:
AudioManageram=mContext.getSystemService(Context.AUDIO_SERVICE);
...
//Requestaudiofocusforplayback
intresult=am.requestAudioFocus(afChangeListener,
//Usethemusicstream.
AudioManager.STREAM_MUSIC,
//Requestpermanentfocus.
AudioManager.AUDIOFOCUS_GAIN);
if(result==AudioManager.AUDIOFOCUS_REQUEST_GRantED){
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
//Startplayback.
}
2)当播放结束时,要abandonAudioFocus,这样之前被打断的app可以重新得到audiofocus,恢复播放:
//Abandonaudiofocuswhenplaybackcomplete
am.abandonAudioFocus(afChangeListener);
3)还要注册OnAudioFocusChangeListener(),这样当audiofocus被别人拿走时,可以及时暂停播放。当别人归还 audiofocus时,可以恢复播放:
OnAudioFocusChangeListenerafChangeListener=newOnAudioFocusChangeListener(){
publicvoidonAudioFocusChange(intfocusChange){
if(focusChange==AUDIOFOCUS_LOSS_TRANSIENT
//Pauseplayback
}elseif(focusChange==AudioManager.AUDIOFOCUS_GAIN){
//Resumeplayback
}elseif(focusChange==AudioManager.AUDIOFOCUS_LOSS){
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
//Stopplayback
}
}
MT6735如何监听手机上面音乐/FM等多媒体声音的播放/停止的动作?
[SOLUTION]
android有一个AudioFocus的机制,要播放声音的app可以去requestAudioFocus(),当拿到audiofocus之后再播放音乐 ,当失去audiofocus的时候做停止播放的动作,当自己的播放动作结束后,释放audiofocus。通过audiofocus可以做到 监听有使用audiofocus的那些app的播放/停止的动作,可以达到在同一时间,只有拿到audiofocus的app才可以播放音 乐的目的,这样可以避免各个app的声音相互冲突。
代码例子如下:
1)要播放时,先requestAudioFocus(),再Startplayback:
AudioManageram=mContext.getSystemService(Context.AUDIO_SERVICE);
...
//Requestaudiofocusforplayback
intresult=am.requestAudioFocus(afChangeListener,
//Usethemusicstream.
AudioManager.STREAM_MUSIC,
//Requestpermanentfocus.
AudioManager.AUDIOFOCUS_GAIN);
if(result==AudioManager.AUDIOFOCUS_REQUEST_GRantED){
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
//Startplayback.
}
2)当播放结束时,要abandonAudioFocus,这样之前被打断的app可以重新得到audiofocus,恢复播放:
//Abandonaudiofocuswhenplaybackcomplete
am.abandonAudioFocus(afChangeListener);
3)还要注册OnAudioFocusChangeListener(),这样当audiofocus被别人拿走时,可以及时暂停播放。当别人归还 audiofocus时,可以恢复播放:
OnAudioFocusChangeListenerafChangeListener=newOnAudioFocusChangeListener(){
publicvoidonAudioFocusChange(intfocusChange){
if(focusChange==AUDIOFOCUS_LOSS_TRANSIENT
//Pauseplayback
}elseif(focusChange==AudioManager.AUDIOFOCUS_GAIN){
//Resumeplayback
}elseif(focusChange==AudioManager.AUDIOFOCUS_LOSS){
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
//Stopplayback
}
}