Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift: Sound not playing

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.

like image 651
Jasper Avatar asked Sep 02 '25 17:09

Jasper


1 Answers

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)
}
like image 198
Leo Dabus Avatar answered Sep 05 '25 07:09

Leo Dabus