改进音频播放

当您尝试使用 USB API 直接访问 USB 音频外围设备时,会出现问题。这些问题可能包括:安全问题、限制其他应用播放媒体,以及通过 USB 设备丢失闹钟、通知和铃声。

如需改进音频播放,请改为配置混音器属性。

配置混音器属性

通过使用 AudioMixerAttributes API,您可以通过 USB 为应用配置首选混音器属性。

当应用播放与首选混音器属性的编码格式、声道掩码和采样率匹配时,播放会附加到其混音器配置了首选混音器属性的音频输出流。

只要 USB 设备支持相应配置,您的应用就可以采用任何配置向硬件抽象层 (HAL) 和设备流式传输音频。

AudioMixerAttributes 中允许的两种混音器行为是 DEFAULT 和 BIT_PERFECT。如果混音器行为为 DEFAULT,则表示来自不同来源的音频数据会混合在一起。

当混音器行为为 BIT_PERFECT 时,系统不会对播放应用任何混音、音量调节或音频处理效果。数据会按原样发送到 HAL,最后发送到 USB 设备。

使用 BIT_PERFECT,您可以在搭载 Android 的设备上通过脉冲编码调制 (PCM) 传输直接流数字 (DSD) 音频。以下代码示例展示了如何实现此目的:

val EXPECTED_FORMAT: AudioFormat = AudioFormat.Builder()
    .setEncoding(AudioFormat.ENCODING_PCM_24BIT_PACKED)
    .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
    .setSampleRate(44100)
    .build()

fun startPlayback() {
    // Query all supported mixer attributes
    val mixerAttributesList: List<AudioMixerAttributes?> =
        mAudioManager.getSupportedMixerAttributes(usbDevice)

    // Find the wanted mixer attributes
    val mixerAttributes = mixerAttributesList.stream()
        .filter { mixerAttr: AudioMixerAttributes? ->
            EXPECTED_FORMAT.equals(
                mixerAttr!!.format
            )
        }
        .findAny()
        .orElse(null) ?: return

    // Register a listener to mixer attributes changed
    val listener = MyPreferredMixerAttributesChangedListener()
    mAudioManager.addOnPreferredMixerAttributesChangedListener(
        Executors.newSingleThreadExecutor(), listener
    )

    // Currently, only media usage over USB devices will be allowed
    val attr: AudioAttributes = AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA).build()
    // Set preferred mixer attributes
    mAudioManager.setPreferredMixerAttributes(
        attr, usbDevice, mixerAttributes
    )

    // Start playback, note the playback and the audio format must
    // match what is set when calling `setPreferredMixerAttriutes`
    // API.
    val audioTrack = AudioTrack.Builder()
        .setAudioAttributes(attr)
        .setAudioFormat(mixerAttributes!!.format)
        .build()

    // Clear all preferred mixer attributes related stuff when
    // playback task is completed
    mAudioManager.clearPreferredMixerAttributes(attr, usbDevice)
    mAudioManager.removeOnPreferredMixerAttributesChangedListener(listener)
}

private class MyPreferredMixerAttributesChangedListener :
    AudioManager.OnPreferredMixerAttributesChangedListener {
    override fun onPreferredMixerAttributesChanged(
        attributes: AudioAttributes,
        device: AudioDeviceInfo,
        mixerAttributes: AudioMixerAttributes?,
    ) {
        // Do something when preferred mixer attributes changed
    }
}