播放/暂停音频按钮Swift

3
我刚开始学习swift,无法解决这个问题。我想让一个按钮既可以作为播放按钮循环音频,也可以在再次点击时作为暂停按钮。我尝试使用if/else语句,但是一直出现错误“fatal error: unexpectedly found nil while unwrapping an Optional value”。如果不使用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()}
代码和错误信息的图片: 代码和错误信息的图片

1
你的代码崩溃是因为在初始化hithat16之前使用了它,即在if语句中。 - Aaqib Hussain
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4

试试这个。

在你的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()}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,