我已经开始学习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
}
但是,当我点击按钮时,我的文件无法播放。这首歌正常播放。
答案 0 :(得分:4)
尝试使用以下代码:
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)
}
}
答案 1 :(得分:3)
您的代码存在很多问题,但这是一个阳光灿烂的日子,所以尝试这样的事情......
func playSound() {
guard let url = Bundle.main.url(forResource: "faded", withExtension: "mp3") else { return }
let bombSoundEffect = try? AVAudioPlayer(contentsOf: url)
bombSoundEffect?.play()
}