播放/暂停音频按钮Swift

时间:2017-06-26 03:54:11

标签: ios swift audio swift3

我是快速的新手,似乎无法弄清楚这一点。我试图让一个按钮充当循环音频的播放按钮和再次单击时的暂停按钮。我尝试过使用if / else语句,但我一直收到此错误“致命错误:在展开Optional值时意外发现nil”

代码在没有if / else语句的情况下工作,但是,在这种情况下,它无限循环而无法暂停它。

有什么建议吗?

 var hihat16: AVAudioPlayer!

     @IBAction func hat16(_ sender: Any) {
        if hihat16.isPlaying == false {
    let path = Bundle.main.path(forResource: "Hat 017-1.aif", ofType:nil)!
    let url = URL(fileURLWithPath: path)

    do {
    let sound = try AVAudioPlayer(contentsOf: url)
    hihat16 = sound
    sound.play()
    hihat16.numberOfLoops = -1


    } catch {
    // couldn't load file :(
    }
        }else{ hihat16.stop()}

代码和错误消息的图片: Picture of the code and error message

1 个答案:

答案 0 :(得分:3)

试试这个。

在viewDidLoad

中执行此操作
let path = Bundle.main.path(forResource: "Hat 017-1.aif", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
hihat16 = try AVAudioPlayer(contentsOf: url)
hihat16.numberOfLoops = -1
} catch {}

然后在你的@IBAction中你可以做到这一点。

if !hihat16.isPlaying {
hithat16.play()
}
else{ hithat.stop()}
相关问题