swiftswiftuiavaudioplayeronappear

SwiftUI on appear AVAudioPlayer plays multiple times


Im trying to add a AVAudioPlayer for background music on my app, I am initiating the player at the main screen, trying to start playing when the app opens but get unexpected behavior...
It plays and instantly keeps sort of creating new players and playing those players so there is tens of the same sound playing at the same time

Initiating and playing function for the music

if let path = Bundle.main.path(forResource: sound, ofType: type) {
    do {
        backgroundPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
        backgroundPlayer?.play()
    } catch {
        print("BACKGROUND MUSIC ERROR")
    }
}

On appear call for the function
.onAppear {
    audioController.backgroundMusic(sound: "bg", type: "wav")
}

Edit: Example code ...

import SwiftUI
import AVKit

struct ContentView: View {
    @ObservedObject var audioController = AudioController()

    var body: some View {
         Text("Hello, world!")
             .onAppear {
                 audioController.playBackgroundMusic(sound: "bg", type: "wav")
             }
    }
}

class AudioController: ObservableObject {
     var player: AVAudioPlayer?    

     func playBackgroundMusic(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                player?.play()
            } catch {
                print("BACKGROUND MUSIC ERROR")
            }
        }
    }
}

Solution

  • Found out it was actually just a "simulator" bug, when the app open from the xcode build it keeps playing the sound over and over ... but after closing and reopening the app, the sound plays as expected.