您需要在activate选项之前设置类别
下面的代码清单显示了设置会话,激活会话和开始播放所需的所有步骤。
// Set up the session. let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSession.Category.playback, mode: .default, policy: .longForm, options: []) } catch let error { fatalError("*** Unable to set up the audio session: \(error.localizedDescription) ***") } // Set up the player. let player: AVAudioPlayer do { player = try AVAudioPlayer(data: audioData) } catch let error { print("*** Unable to set up the audio player: \(error.localizedDescription) ***") // Handle the error here. return } // Activate and request the route. audioSession.activate(options: []) { (success, error) in guard error == nil else { print("*** An error occurred: \(error!.localizedDescription) ***") // Handle the error here. return } // Play the audio file. player.play() }