gpt4 book ai didi

ios - 如何在 swift3 中播放 mp3 文件?

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:35 25 4
gpt4 key购买 nike

开始学习ios开发,卡在一个地方。我播放 mp3 文件的代码是

var bombSoundEffect: AVAudioPlayer!
let path = Bundle.main.path(forResource: "faded", ofType:"mp3")!
let url = NSURL(fileURLWithPath: path)

do {
let sound = try AVAudioPlayer(contentsOf: (url as NSURL) as URL)
bombSoundEffect.play()

} catch {
print("couldn't load file :(")
}
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}

但是,当我点击按钮时,我的文件没有播放。这首歌正在正常播放。

最佳答案

尝试使用以下代码:

var bombSoundEffect: AVAudioPlayer?

func playAudio() {
let url = Bundle.main.url(forResource: "faded", withExtension: "mp3")!

do {
bombSoundEffect = try AVAudioPlayer(contentsOf: url)
guard let bombSound = bombSoundEffect else { return }

bombSound.prepareToPlay()
bombSound.play()
} catch let error {
print(error.localizedDescription)
}
}

关于ios - 如何在 swift3 中播放 mp3 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com