在这里,我附上我的代码和权限屏幕快照,请在这里告诉我们什么问题
我已经尝试过使用该网址https://developer.apple.com/documentation/watchkit/playing_background_audio的Apple开发人员指南
但仍然无法正常工作。
func play(url : URL) {
if #available(watchOSApplicationExtension 5.0, *) {
do {
WKExtension.shared().isFrontmostTimeoutExtended = true
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: AVAudioSession.Category.playback.rawValue), mode: AVAudioSession.Mode.moviePlayback, options: AVAudioSession.CategoryOptions.duckOthers)
} catch let error {
print("** Unable to set up the audio session: \(error.localizedDescription) **")
// Handle the error here.
return
}
do {
self.player = try AVAudioPlayer(contentsOf: url)
// player!.prepareToPlay()
player?.delegate = self
} catch let error {
print("** Unable to set up the audio player: \(error.localizedDescription) **")
// Handle the error here.
return
}
print("\nPlaying audio!")
self.player?.play()
// Activate and request the route.
audioSession?.activate(options: []) { (success, error) in
print("Success \(success)")
print("error \(String(describing: error))")
guard error == nil else {
print("** An error occurred: \(error!.localizedDescription) **")
// Handle the error here.
return
}
// Play the audio file.
if success {
} else {
print("audio session activation failded")
}
}
} else {
print("alert")
}
}
答案 0 :(得分:-1)
您需要在激活选项之前设置类别
下面的代码清单显示了设置会话,激活会话并开始播放所需的所有步骤。
// 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()
}