当我不放手的时候,如何继续在iWatch应用中播放音频? -watchOS

时间:2019-03-11 10:20:56

标签: ios swift apple-watch watch-os

我正在尝试为Apple Watch构建音频应用程序。但是问题是,只要我放开手,音频就会停止播放。 我也打开了背景模式。 谁能帮我这个忙吗?我被困在这一部分。 这是我用来播放音频的代码。

func play(url : URL) {
        do {
            if #available(watchOSApplicationExtension 4.0, *) {
                WKExtension.shared().isFrontmostTimeoutExtended = true
            } else {
                // Fallback on earlier versions
            }
            self.player = try AVAudioPlayer(contentsOf: url)
                player!.prepareToPlay()
            player?.delegate = self
            player?.play()
            print("-----------------")
            print("Playing Audio")
            print("*****************\nCurrent Time \(String(describing: self.player?.currentTime))")
        } catch let error as NSError {
            self.player = nil
            print(error.localizedDescription)
        } catch {
            print("*************************")
            print("AVAudioPlayer init failed")
        }
    }

2 个答案:

答案 0 :(得分:1)

仅打开后台模式是不够的。您还需要激活AVAudioSession
Apple对此进行了充分的记录:Playing Background Audio

  

配置并激活音频会话

     

在播放音频之前,您需要设置并激活音频会话。

session.setCategory(AVAudioSession.Category.playback,
                    mode: .default,
                    policy: .longForm,
                    options: [])
     

接下来,通过调用activate(options:completionHandler :)方法来激活会话。

session.activate(options: []) { (success, error) in
    // Check for an error and play audio.
}
     

参考:https://developer.apple.com/documentation/watchkit/playing_background_audio


示例:

var player: AVAudioPlayer?
let session: AVAudioSession = .sharedInstance()

func prepareSession() {
    do {
        try session.setCategory(AVAudioSession.Category.playback,
                                mode: .default,
                                policy: .longForm,
                                options: [])
    }
    catch {
        print(error)
    }
}

func play(url: URL) {
    do {
        player = try AVAudioPlayer(contentsOf: url)
    }
    catch {
        print(error)
        return
    }

    session.activate(options: []) { (success, error) in
        guard error == nil else {
            print(error!)
            return
        }

        // Play the audio file
        self.player?.play()
    }
}

简单测试:

prepareSession()

if let url = Bundle.main.url(forResource: "test", withExtension: "mp3") {
    play(url: url)
}
else {
    print("test.mp3 not found in project: put any mp3 file in and name it so")
}

答案 1 :(得分:1)

请确保在这里您尝试使用Audio Data而不是Audio URL进行付款,并在类别设置中添加了policy: .longForm。根据Apple文档,在后台模式下播放音频必须具备这两项设置

// Set up the session. let session = AVAudioSession.sharedInstance()

    do {
        try session.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. session.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() 

}

我已经测试了此代码,并且仅在Watch应用程序中而非蓝牙扬声器中使用了蓝牙连接。