Game Development Reference
In-Depth Information
NSError *error;
AVAudioPlayer *backgroundAudioPlayer = [AVAudioPlayer
alloc] initWithContentsOfURL:file error:&error];
8. After that call a prepareToPlay method on the AVAudioPlayer object so
that it prepares the audio file to be played.
[backgroundAudioPlayer prepareToPlay];
9. Before playing the audio file, we can set the volume and numberOfLoops
and lastly we can play the audio file.
backgroundAudioPlayer.volume = 1.0;
backgroundAudioPlayer.numberOfLoops = -1;
[backgroundAudioPlayer play];
AVAudioPlayer
AVAudioPlayer is a modern way of playing and doing more things with audio. It supports
audio files encoded with AAC and MP3, which are not supported by System Sound Ser-
vices. Moreover, there is an easy way to play music through a class name AVAudi-
oPlayer , which is treated as a player for every music or sound effect.
To accomplish this, perform the following steps:
1. First we have to import AVFoundation :
@import AVFoundation;
2. Then use this snippet to play a sample sound using an object of AVAudioPlayer:
NSString *samplePath = [[NSBundle mainBundle]
pathForResource:@"sample-sound.caf" ofType:nil];
NSURL *file = [NSURL fileURLWithPath:samplePath];
NSError *error;
AVAudioPlayer *backgroundAudioPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL:file
error:&error];
[backgroundAudioPlayer prepareToPlay];
backgroundAudioPlayer.numberOfLoops = -1;
Search WWH ::




Custom Search