在我的 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 添加到应用程序中。在 Debug模式下,我可以看到 soundURL 有一个值,但它不是 nil。
没有错误,但没有播放声音。
最佳答案
您只需将 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)
}
关于iOS swift : Sound not playing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986446/