改善音訊播放品質

當您嘗試使用 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
    }
}