点击 watchOS 按钮即可播放本地声音

问题描述 投票:0回答:1

我是快速开发和为苹果手表构建一个简单应用程序的新手。我希望在点击按钮时播放短促的声音。这可能吗?

据我了解,最好的方法是使用 AVFoundation 和 AVAudioPlayer。在过去的几个版本中似乎有很多关于此的更新,并且我发现了相互矛盾的建议。基于一些教程,我将这个简单的测试放在一起,但我得到了 “线程 1:致命错误:展开可选值时意外发现 nil” 这是我的代码:

import WatchKit
import Foundation
import AVFoundation

var dogSound = AVAudioPlayer()


class InterfaceController: WKInterfaceController {

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        // Configure interface objects here.
    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }

    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

    @IBAction func playTapped() {

        let path = Bundle.main.path(forResource: "Dog", ofType: ".mp3")!
        let url = URL(fileURLWithPath: path)

        do {
            dogSound = try AVAudioPlayer(contentsOf: url)
            dogSound.play()
        } catch {
            //couldn't load file :(
        }

    }
}

我的音频文件是一个名为 Dogmp3,位于 WatchKit Extension 中的 Assets.xcassets 文件夹中,我已将 AVFoundation.framework 添加到 Link Binary with Libraries

我做错了什么?是否有正确的方法来实现这一点的教程?非常感谢!

swift avfoundation watchkit avaudioplayer watchos
1个回答
0
投票

使用 AVSession 代替:

import Foundation
import AVFAudio

final class AudioManager {
     var audioPlayer: AVAudioPlayer?
    static let shared = AudioManager()
}


extension AudioManager: AudioManagerProtocol {

func start() {
    play("start")
}

fileprivate func play(_ filename: String) {
    guard let soundURL = Bundle.main.url(forResource: filename, withExtension: "mp3") else { return }
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
        audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        audioPlayer?.play()
    } catch {
        print("Error al inicializar el reproductor de audio: \(error.localizedDescription)")
    }
}
}

在我的例子中,我包含了一个名为“start.mp3”的文件:

© www.soinside.com 2019 - 2024. All rights reserved.