我用这个网址https://developer.apple.com/documentation/watchkit/playing_background_audio尝试了苹果开发者指南
但仍然没有工作。
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")
}
}
您需要在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()
}