Mike Walker
Mike Walker

Reputation: 3166

Unable to Play Audio Using AVAudioPlayer

I am attempting to play an audio file using AVAudioPlayer. Previously, I was able to play audio successfully using the code:

// Play the audio file
var soundID: SystemSoundID = 0
let mainBundle: CFBundleRef = CFBundleGetMainBundle()
// Get the audio reference
if let ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, filename, Globals.SOUND_TYPE, nil) {
    // Reference found, play audio
    AudioServicesCreateSystemSoundID(ref, &soundID)
    AudioServicesPlaySystemSound(soundID)
}

But a new requirement in the app is I will need to be able to play audio with a certain volume. AudioServicesPlaySystemSound is not able to give me that functionality. So now I have the following code:

do {
    let audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(filename, ofType: Globals.SOUND_TYPE)!))

    audioPlayer.volume = volume
    audioPlayer.play()
    print("play audio")

} catch {
    print("Error")
}

I'm getting to the play audio print statement, but not audio is playing. I have even hardcoded audioPlayer.volume = 1.0, but no audio plays. What code could I be missing in order to play the audio?

Upvotes: 1

Views: 279

Answers (1)

Daniel Zhang
Daniel Zhang

Reputation: 5858

Your local audioPlayer variable is being released before the sound can play.

If you add a property (instance variable) for the player and use that instead, the player will have a chance to play the sound before being deallocated.

In your class, create a property like

var audioPlayer: AVAudioPlayer?

Then, instead of

let audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(filename, ofType: Globals.SOUND_TYPE)!))

use a reference to the property

self.audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(filename, ofType: Globals.SOUND_TYPE)!))

where the self is not required in Swift.

Upvotes: 1

Related Questions