在我的iOS
Swift应用程序中,我想点击一个按钮播放声音.
func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell",withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL,error: nil) audioPlayer.play() }
我正在iOS iPhone模拟器中运行该应用程序.
我已将doorbell.mp3添加到应用程序中.在调试模式下,我可以看到soundURL有一个值,它不是零.
没有错误,但声音没有播放.
解决方法
您只需要从您的方法中移出audioPlayer的声明.试试这样:
Swift 3或更高版本
var audioPlayer = AVAudioPlayer() func playSound() throws { let url = Bundle.main.url(forResource: "doorbell",withExtension: "mp3")! audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer.prepareToPlay() audioPlayer.play() }
do { try playSound() } catch { print(error) }