0
votes

I know it seems quite straightforward, but in a weird way AVAudioPlayer does not play audio file. I have this code. It is not go through catch and still sound does not play. I've checked on physical device, simulator and also checked sound volume. But still I can't hear sound.

//in ViewController as a property
let soundEffect: AVAudioPlayer!

//in viewDidLoad
let path = Bundle.main.path(forResource: "success.mp3", ofType:nil)!
    let url = URL(fileURLWithPath: path)
    do {
        soundEffect = try AVAudioPlayer(contentsOf: url)
        soundEffect.prepareToPlay()
        soundEffect.play()
    } catch let error as NSError {
        print(error.description)
    }

I also tried let path = Bundle.main.path(forResource: "success", ofType:"mp3")! but it didn't make any difference.

1

1 Answers

1
votes

Try making your AVAudioPlayer an instance variable. otherwise soundEffect is deallocated at the end of the do loop.