简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM