AVAudioPlayer not playing any sound

by

The most common culprit causing AVAudioPlayer not playing sound is ARC. When my audio player's scope is just within a function ARC deallocates the memory before playing sound after function is called. Here is an example code:


func playSoundEffect(assetName: string?) {
    if let sound = assetName{
        if let asset = NSDataAsset(name:sound){
            
            do {
                // Use NSDataAsset's data property to access the audio file stored in Sound.
                let soundEffect = try AVAudioPlayer(data:asset.data, fileTypeHint:"wav")
                // Play the above sound file.
                soundEffect?.play()
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
    }
}

In code soundEffect is declared and initialised inside the function. When I call this function there is no sound. I assumed that ARC will kick in after audio player finishes playing sound. But that is not the case.

If I declare the soundEffect as optional instance variable which creates it’s scope within the lifecycle of instance of the class and assuming that instance of class is alive then I hear sound playing because audio player isn’t deallocated.
private var soundEffect:AVAudioPlayer?


private var soundEffect:AVAudioPlayer?

func playSoundEffect(assetName: string?) {
    if let sound = assetName{
        if let asset = NSDataAsset(name:sound){
            
            do {
                // Use NSDataAsset's data property to access the audio file stored in Sound.
                soundEffect = try AVAudioPlayer(data:asset.data, fileTypeHint:"wav")
                // Play the above sound file.
                soundEffect?.play()
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }
    }
}

This is minor thing to keep in mind. I spent time on investigating if my audio file was corrupted or naming was misspelled.

You might also like: MFMessageComposeViewController shows blank white screen issue

You might also like: Sort an array of string containing numbers

More Articles

Recommended posts