“尝试 AVAudioSession.sharedInstance().setCategory”仅在设备上返回 nil

Zac*_*ack 4 iphone ios swift

try AVAudioSession.sharedInstance()
                  .setCategory(AVAudioSessionCategoryPlayback,
                               with: AVAudioSessionCategoryOptions(rawValue: UInt(UInt8(AVAudioSessionCategoryOptions.defaultToSpeaker.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowAirPlay.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowBluetooth.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowBluetoothA2DP.rawValue))))
Run Code Online (Sandbox Code Playgroud)

返回错误:

域=NSOSStatusErrorDomain 代码=-50“(空)”

Zac*_*ack 7

对于将来发现此问题的任何人来说,这里就是解决方案。如果您更改AVAudioSessionCategoryPlaybackAVAudioSessionCategoryPlayAndRecord这样,它仅适用于设备:

try AVAudioSession.sharedInstance()
                  .setCategory(AVAudioSessionCategoryPlayAndRecord,
                               with: AVAudioSessionCategoryOptions(rawValue: UInt(UInt8(AVAudioSessionCategoryOptions.defaultToSpeaker.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowAirPlay.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowBluetooth.rawValue)
                                                                                | UInt8(AVAudioSessionCategoryOptions.allowBluetoothA2DP.rawValue))))
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是因为 .allowAirPlay CategoryOption 仅适用于类别 PlayAndRecord:https://developer.apple.com/documentation/avfoundation/avaudiosession/categoryoptions/1771736-allowairplay (2认同)