iOS Swift:声音没有播放 [英] iOS Swift: Sound not playing
本文介绍了iOS Swift:声音没有播放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的iOS Swift应用程序中,我试图点击按钮播放声音。
In my iOS Swift application, and i am trying to play sound on click of a button.
func playSound()
{
var audioPlayer = AVAudioPlayer()
let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3")
audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
audioPlayer.play()
}
I我在iOS iPhone模拟器中运行应用程序。
我已将doorbell.mp3添加到应用程序中。在调试模式下,我可以看到soundURL有一个值,它不是零。
I am running the application in iOS iPhone Simulator. I have doorbell.mp3 added to the application. In debug mode i can see that soundURL has a value and it is not nil.
没有错误,但声音没有播放。
There are no errors, but the sound does not play.
推荐答案
您只需要将audioPlayer的声明移出您的方法。试试这样:
You just need to move the declaration of your audioPlayer out of your method. Try like this:
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:声音没有播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文