【问题标题】:Play/Pause Audio Button Swift播放/暂停音频按钮 Swift
【发布时间】:2017-06-26 03:54:10
【问题描述】:

我是 swift 新手,似乎无法弄清楚这一点。我试图让一个按钮既充当循环音频的播放按钮,又充当暂停按钮(如果再次单击)。我尝试使用 if/else 语句,但我不断收到此错误“致命错误:在展开可选值时意外发现 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()}

代码和错误信息的图片:

【问题讨论】:

  • 您的代码正在崩溃,因为您在初始化之前使用了 hithat16。即在 if 语句中。

标签: ios swift audio swift3


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2015-04-03
    • 1970-01-01
    相关资源
    最近更新 更多