Zorgan
Zorgan

Reputation: 9123

Audio from AVAudioPlayer doesn't make a sound

Here is the code that does not work (sound successfully plays but doesn't make a sound):

struct MultipleChoiceOption: View {
    let soundManager = SoundManager()

    var body: some View {
        Button(action: {
            SoundManager().playSound(name: "click.wav")

Whereas this code does work:

struct MultipleChoiceOption: View {
    let soundManager = SoundManager()

    var body: some View {
        Button(action: {
            self.soundManager.playSound(name: "click.wav")

Viewmodel

class SoundManager: ObservableObject {
    var player: AVAudioPlayer?
    
    func playSound(name: String){
        let path = Bundle.main.path(forResource: name, ofType: nil)
        let url = URL(fileURLWithPath: path!)
        print("Play URL from name: \(name)")
        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            print("Played sound")
        } catch {
            print("Error playing \(name) sound")
        }
    }
}

I don't get it. Why does the second code block work but the first doesn't?

Upvotes: 1

Views: 37

Answers (1)

fishinear
fishinear

Reputation: 6336

Think a bit about what the two approaches actually do. In the second case, you create a SoundManager object and assign it to a variable that is part of your MultipleChoiceOption object. Therefore, it will live as long as the MultipleChoiceOption object is alive. Then you use that SoundManager to play the sound.

In the first case, you create an other SoundManager object when the button is pressed, but never assign it to a variable. That is, it will live until the end of the action method and then be terminated immediately, long before it manages to play sound.

Upvotes: 1

Related Questions