虽然我保持手腕,但如何在iWatch应用程序中继续播放音频? - watchOS

问题描述 投票:3回答:2

我正在尝试为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")
        }
    }
ios swift apple-watch watch-os
2个回答
1
投票

请确保在这里你尝试用Audio Data支付Audio URL,并在你的类别设置中添加policy: .longForm。根据苹果文档,在后台模式下进行音频播放时必须使用这两个设置

// 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应用程序中的蓝牙连接,而不是手表扬声器。


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


Example:

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()
    }
}

Simple Test:

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")
}
© www.soinside.com 2019 - 2024. All rights reserved.