I am using the AVFoundation framework to play a sound. At the beginning of the file, I have:
#import <AVFoundation/AVAudioPlayer.h>
And the AVFoundation framework is properly added to my project. However, when I use this code to play a sound, the app crashes:
NSString *pathForBgMusicFile = [[NSBundle mainBundle] pathForResource:@"ClenchedTeeth" ofType:@"mp3"];
NSURL *bgMusicFile = [[NSURL alloc] initFileURLWithPath:pathForBgMusicFile];
AVAudioPlayer *bgMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:bgMusicFile error:NULL];
[bgMusic play];
Does anyone know how to fix this? Thanks in advance!
Try setting up the
AVAudioSessionas well before you attempt playback. Like this:Remember to import it, and make sure your class implements both
AVAudioPlayerDelegateandAVAudioSessionDelegate.