3

在此处输入图像描述在这里我附上我的代码和权限屏幕截图请咨询这里有什么问题

我已经尝试使用此网址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")
        }
    }
4

1 回答 1

-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()
}
于 2019-03-13T15:45:44.420 回答