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 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.
You just need to move the declaration of your audioPlayer out of your method. Try like this:
Swift 3 or later
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With