AUAudioUnit 无法在后台播放音频错误代码 561145187

AUAudioUnit can't play audio in the background error code 561145187

我正在使用 AUAudioUnit 播放应用程序从服务器流式传输的音频。我的代码在前台运行良好。但是当我为应用程序设置后台时,它不会播放音频。我收到以下错误。

[aurioc] AURemoteIO.cpp:1590:Start: AUIOClient_StartIO failed (561145187)

错误代码561145187表示AVAudioSessionErrorCodeCannotStartRecording

This error type usually occurs when an app starts a mixable recording from the background and it isn’t configured as an Inter-App Audio app.

这就是我在 Swift 中设置 AVAudioSession 的方式:

try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .voiceChat, options: [.allowBluetooth])

这就是我在 Objective-C 中设置 AUAudioUnit 的方式:

AudioComponentDescription description;
description.componentType = kAudioUnitType_Output;
description.componentSubType = kAudioUnitSubType_VoiceProcessingIO;
description.componentManufacturer = kAudioUnitManufacturer_Apple;
description.componentFlags = 0;
description.componentFlagsMask = 0;

self.format = [[AVAudioFormat alloc] initWithSettings: @{
                                                       AVFormatIDKey: @(kAudioFormatLinearPCM),
                                                       AVSampleRateKey: @16000,
                                                       AVNumberOfChannelsKey: @1,
                                                       AVLinearPCMIsFloatKey: @NO,
                                                       AVLinearPCMBitDepthKey: @16,
                                                       AVLinearPCMIsBigEndianKey: @NO
                                                       }];

self.audioUnit = [[AUAudioUnit alloc] initWithComponentDescription:description options:0 error:nil];

当我调用 startHardwareAndReturnError 方法时,就是我收到该错误消息的时候。

[self.unit startHardwareAndReturnError:outError];

我已经设置了后台模式 - 音频功能。而且我很确定我设置了 AVAudioSession 所以它是不可混合的。我什至不录音。我只是想播放音频。我还缺少什么?

要在后台录制音频,您必须在前台启动音频单元。然后音频单元将在后台继续运行。如果没有数据播放,可以静音播放。

如果您不录制音频,则不要使用 playAndRecord 会话类型。请改用其中一种仅播放会话类型。