Why am I getting this error?

It would be better to create a class that is a SoundManager like this:

class SoundManager {
    static var audioPlayer: AVAudioPlayer?

    static func playMusic() {
        let soundFilename = "cleansing_clearing_breath"
        let bundlePath = Bundle.main.path(forResource: soundFilename, ofType: "mp3")

        guard bundlePath != nil else {
            print("Couldn't find sound file \(soundFilename) in the bundle")
            return
        }

        //  Create a URL object from this string path
        let soundURL = URL(fileURLWithPath: bundlePath!)

        do {
            //  Create audio player object
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)

            //  Play the sound
            audioPlayer?.play()

        } catch {
            // Could not create audio player object
            print("Could not create the audio player object for sound file \(soundFilename).")
        }
    }
}

and then change your AudioPlayerView to this:

import SwiftUI

struct AudioPlayerView: View {

    var body: some View {

        VStack {
            Text("Play")
                .font(.largeTitle)
            HStack {
                Spacer()
                Button(action: {
                    SoundManager.playMusic()
                }) {
                    Image(systemName: "play.circle.fill")
                        .resizable()
                        .frame(width: 50, height: 50)
                        .aspectRatio(contentMode: .fit)
                }
                Spacer()
                Button(action: {
                    SoundManager.audioPlayer?.stop()
                }) {
                    Image(systemName: "pause.circle.fill")
                        .resizable()
                        .frame(width: 50, height: 50)
                        .aspectRatio(contentMode: .fit)
                }
                Spacer()
            }
        }
        .onAppear {
            SoundManager.playMusic()
        }

    }
}
2 Likes