Handling audio focus
Even though only one activity can run at any given time, Android is amulti-tasking environment. This poses a particular challenge to applications that use audio, because there is only one audio output and there may be several media services competing for its use. Before Android 2.2, there was no built-in mechanism to address this issue, which could in some cases lead to a bad user experience. For example, when a user is listening to music and another application needs to notify the user of something very important,the user might not hear the notification tone due to the loud music. Starting withAndroid 2.2, the platform offers a way for applications to negotiate their use of the device's audio output. This mechanism is called Audio Focus.
虽然在任意一个给定时间,只有一个activity能运行,android也是一个多任务环境。这给应用程序使用音频带来了一个特殊的挑战,因为只有一个音频输出,并且可能有几个媒体服务争夺使用这个音频输出。在Android 2.2之前,没有内建的机制来解决这个问题,这个问题在一些case下能导致一个坏的用户体验。例如,在用户正在听音乐时,其他应用需要通知用户非常重要的事情,用户可能不会听到通知铃声,因为声音很大的音乐。从Android 2.2 开始,平台提供一个方法为应用,为了让这些播放音频的应用协调他们如何使用设备的音频输出。这个机制被叫做音频焦点。
When your application needs to output audio such as music or a notification,you should always request audio focus. Once it has focus, it can use the sound output freely, but it should always listen for focus changes. If it is notified that it has lost the audiofocus, it should immediately either kill the audio or lower it to a quiet level(known as "ducking"—there is a flag that indicates which one is appropriate) and only resumeloud playback after it receives focus again.
当你的应用需要输出像是音乐或者通知这样的音频,你总是应该请求音频焦点。一旦你的app拥有焦点,它就能自由的使用声音输出,但是它应该总是监听焦点的改变。如果它被通知它已经失去了音频焦点,它就应该立即杀掉音频或者降低它的音量到静音的水平(被称为“ducking”- 有一个标记,用来表明哪一个是适合的),并且只能在它接收到焦点再次获取时恢复回放。
Audio Focus is cooperative in nature. That is, applications are expected(and highly encouraged) to comply with the audio focus guidelines, but the rules are not enforced by the system. If an application wants to play loud music even after losing audio focus, nothing in the system will prevent that.However, the user is more likely to have a bad experience and will be more likely to uninstall the misbehaving application.
音频焦点本质上是合作机制。这就是,应用被期望遵守音频焦点指导方针,但是这个规则不是被系统强力执行的。如果一个应用想要继续大声播放音乐,甚至在失去音频焦点后,系统中不会有任何东西来阻止它。然而,用户更可能有一个坏的体验,并且将会更可能卸载掉这样行为不端的应用。
To request audio focus, you must call requestAudioFocus()
from the AudioManager
, as the example below demonstrates:
为了请求音频焦点,你必须从AudioManager调用 requestAudioFocus() 函数 , 像下面示范的例子:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);