PruitIgoe
PruitIgoe

Reputation: 6384

Swift 3: AVAudioPlayer not playing sound

I have a struct with my audio player in it:

struct MT_Audio {

    func playAudio(_ fileName:String, _ fileExtension:String,  _ atVolume:Float) {
        var audioPlayer = AVAudioPlayer()
        if let  audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
            let audioURL = URL(string:audioPath)
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
                audioPlayer.volume = atVolume
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
        }
    }
}

//I'm calling it in viewDidLoad like this: 

    guard let fileURL = Bundle.main.url(forResource:"heartbeat-01a", withExtension: "mp3") 
         else {
                print("can't find file")
                return
            }

       let myAudioPlayer = MT_Audio() //<--RESOLVED THE ISSUE BY MAKING THIS A PROPERTY OF THE VIEWCONTROLLER
       myAudioPlayer.playAudio("heartbeat-01a", "mp3", 1.0)

Since it doesn't crash and burn on the guard I know the file is there. I've also put a break point in after the try and I am getting to the audio player. When I go to the actual file and click on it in Xcode it plays. This fails on both the sim and device. Any help would be appreciated.

Upvotes: 1

Views: 1721

Answers (1)

mrtnf
mrtnf

Reputation: 132

Looks like your audioPlayer is only stored within your playAudio function.

Try to keep the audioPlayer as an variable inside your class like this:

struct MT_Audio {

    var audioPlayer: AVAudioPlayer?

    mutating func playAudio(_ fileName:String, _ fileExtension:String,  _ atVolume:Float) {

        // is now member of your struct -> var audioPlayer = AVAudioPlayer()
        if let  audioPath = Bundle.main.path(forResource: fileName, ofType: fileExtension) {
            let audioURL = URL(string:audioPath)
            do {
                let audioPlayer = try AVAudioPlayer(contentsOf: audioURL!)
                audioPlayer.volume = atVolume
                audioPlayer.prepareToPlay()
                audioPlayer.play()
            } catch {
                print(error)
            }
        }
    }
}

Upvotes: 3

Related Questions