为什么 Android AudioTrack 中出现此错误? AudioTrackShared: releaseBuffer: mUnreleased 超出范围

Why this error in Android AudioTrack? AudioTrackShared: releaseBuffer: mUnreleased out of range

我正在尝试在应用程序之间广播音频。这是我的音频记录:

private var audiorecord: AudioRecord? = null
private val SAMPLER = 16000 //Sample Audio Rate
private val CHANNEL_CONFIG: Int = AudioFormat.CHANNEL_IN_MONO
private val AUDIO_FORMAT: Int = AudioFormat.ENCODING_PCM_16BIT
private var BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLER, CHANNEL_CONFIG, AUDIO_FORMAT)

    audiorecord = AudioRecord(
        MediaRecorder.AudioSource.MIC,
        SAMPLER,
        CHANNEL_CONFIG,
        AUDIO_FORMAT,
        BUFFER_SIZE
    )

通过 WebSocket 连接发送这个并尝试在 AudioTrack 中播放我遇到了非音频错误:(我正在使用 phone,所以我听到一些噪音,但不是声音)

A/AudioTrackShared: releaseBuffer: mUnreleased out of range, !(stepCount:4 <= mUnreleased:0 <= mFrameCount:22050), BufferSizeInFrames:22050

A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 9569 (Thread-3), pid 18292 (mple.testaudio2)

我的音轨:

    var BUFFER_SIZE = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_VOICE_CALL)

    val attribBuilder = AudioAttributes.Builder()
    attribBuilder.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
    attribBuilder.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)

    val attributes = attribBuilder.build()

    // Build audio format

    val afBuilder = AudioFormat.Builder()
    afBuilder.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
    afBuilder.setEncoding(AudioFormat.ENCODING_PCM_8BIT)
    afBuilder.setSampleRate(BUFFER_SIZE)

    val format = afBuilder.build()


    audioTrack = AudioTrack(
        attributes,
        format,
        BUFFER_SIZE,
        AudioTrack.MODE_STREAM,
        AudioManager.AUDIO_SESSION_ID_GENERATE
    )

我不确定音频属性和音频格式。此代码破坏了我的应用程序。为什么?

一个可能的问题是您在构造函数中传递的第三个参数:

audioTrack = AudioTrack(
    attributes,
    format,
    BUFFER_SIZE, <-- this one
    AudioTrack.MODE_STREAM,
    AudioManager.AUDIO_SESSION_ID_GENERATE
)

根据docs,这应该是以字节为单位的缓冲区大小。您正在传递 BUFFER_SIZE,根据名称似乎是正确的,但该变量定义为

var BUFFER_SIZE = AudioTrack.getNativeOutputSampleRate(AudioManager.STREAM_VOICE_CALL)

所以它实际上是采样率,而不是缓冲区大小。我建议您重命名该变量,该名称具有误导性。您可以尝试为缓冲区大小设置一个较大的数字,看看它是否能解决您的问题。