在应用程序开发过程中,良好的用户体验应该是可预期且可控的。如果我们的应用程序可以播放音频,那么显然我们需要做到能够通过硬件按钮,软件按钮,蓝牙耳麦等来控制音量。 同样地,我们需要能够对应用的音频流进行播放(Play),停止(Stop),暂停(Pause),跳过(Skip),以及回放(Previous)等动作,并且并确保其正确性。
1.明确使用的音频流
Android为播放音乐,闹铃,通知铃,来电声音,系统声音,打电话声音与拨号声音分别维护了一个独立的音频流。这样做的主要目的是让用户能够单独地控制不同的种类的音频。
/** The audio stream for phone calls */
public static final int STREAM_VOICE_CALL = AudioSystem.STREAM_VOICE_CALL;
/** The audio stream for system sounds */
public static final int STREAM_SYSTEM = AudioSystem.STREAM_SYSTEM;
/** The audio stream for the phone ring */
public static final int STREAM_RING = AudioSystem.STREAM_RING;
/** The audio stream for music playback */
public static final int STREAM_MUSIC = AudioSystem.STREAM_MUSIC;
/** The audio stream for alarms */
public static final int STREAM_ALARM = AudioSystem.STREAM_ALARM;
/** The audio stream for notifications */
public static final int STREAM_NOTIFICATION = AudioSystem.STREAM_NOTIFICATION;
/** @hide The audio stream for phone calls when connected to bluetooth */
public static final int STREAM_BLUETOOTH_SCO = AudioSystem.STREAM_BLUETOOTH_SCO;
/** @hide The audio stream for enforced system sounds in certain countries (e.g camera in Japan) */
public static final int STREAM_SYSTEM_ENFORCED = AudioSystem.STREAM_SYSTEM_ENFORCED;
/** The audio stream for DTMF Tones */
public static final int STREAM_DTMF = AudioSystem.STREAM_DTMF;
/** @hide The audio stream for text to speech (TTS) */
public static final int STREAM_TTS = AudioSystem.STREAM_TTS;
2.使用硬件音量键控制Activity音量
默认情况下,按下音量控制键会调节当前被激活的音频流,如果我们的应用当前没有播放任何声音,那么按下音量键会调节响铃的音量。对于游戏或者音乐播放器而言,即使是在歌曲之间无声音的状态,或是当前游戏处于无声的状态,用户按下音量键的操作通常都意味着他们希望调节游戏或者音乐的音量。
此时,你可能希望通过监听音量键被按下的事件,来调节音频流的音量。其实大可不必,因为已经Android为我们提供了setVolumeControlStream(int streamType)方法来直接控制指定的音频流。
/**
* Suggests an audio stream whose volume should be changed by the hardware
* volume controls.
* <p>
* The suggested audio stream will be tied to the window of this Activity.
* Volume requests which are received while the Activity is in the
* foreground will affect this stream.
* <p>
* It is not guaranteed that the hardware volume controls will always change
* this stream's volume (for example, if a call is in progress, its stream's
* volume may be changed instead). To reset back to the default, use
* {@link AudioManager#USE_DEFAULT_STREAM_TYPE}.
*
* @param streamType The type of the audio stream whose volume should be
* changed by the hardware volume controls.
*/
public final void setVolumeControlStream(int streamType) {
getWindow().setVolumeControlStream(streamType);
}
在明确应用程序会使用哪个音频流之后,我们需要在应用程序生命周期的早期阶段调用该方法,因为该方法只需要在Activity整个生命周期中调用一次。通常,我们可以在负责控制多媒体的Activity或者Fragment的onCreate()方法中调用它。这样能确保不管应用当前是否可见,音频控制的功能都能符合用户的预期。
setVolumeControlStream(AudioManager.STREAM_MUSIC);
自此之后,不管目标Activity或Fragment是否可见,按下设备的音量键都能够影响我们指定的音频流(在这个例子中,音频流是"STREAM_MUSIC")。
网友评论