Swift- Why I Can't Play The Sound?

404 Views Asked by At

Why this isn't working? I searched to ways of adding sound into a Xcode and I saw so many different ways. I thought I figured it out how the system's working but something is going wrong but I can't see the problem.

import AVFoundation
var audioPlayer = AVAudioPlayer!

func playSound(sound: String){
        let url = Bundle.main.url(forResource: sound, withExtension: "mp3")
        audioPlayer = try! AVAudioPlayer(contentsOf: url!)
        audioPlayer.play()
    }

 if userGotItRight{
            //true answer
            playSound(sound: "CorrectAnswer")
            
        }else{
            //false answer
            playSound(sound: "WrongAnswer")
            
        }
1

There are 1 best solutions below

0
On

if you want to play a sound which is in your local, you can use this:

import AVFoundation

var player: AVAudioPlayer?

func playSound(_ soundName: String) {
    guard let url = NSBundle.mainBundle().URLForResource(soundName, withExtension: "mp3") else { 
        print("URL is wrong") return
    }
    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()

    } catch {
       print(error.description)
    }
}

then you can call that function like this:

if userGotItRight {
    playSound("CorrectAnswer") 
} else {
    playSound("WrongAnswer")
}