Please consider subscribing to Mobile Developer Tips RSS feed or following us on Twitter
|
|
|
I previously wrote about using Audio Session Services which offers a quick and easy approach for playing short sounds. However, there are a number of limitations, including no control over the volume, playing time is limited to 30 seconds and the only file types supported are AIFF, WAV and CAF.
Sounds with AVAudioPlayer
AVAudioPlayer offers a much wider range of capabilites, including pausing playback, adjusting the volume, tinkering with the playback time (setting and detecting) as well as features for monitoring audio peaks and averages.
The code below shows the basics for setting up a player and playing a sound:
AVAudioPlayer *player;
NSString *path;
NSError *error;
// Path the audio file
path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"];
// If we can access the file...
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
// Setup the player
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:&error];
// Set the volume (range is 0 to 1)
player.volume = 0.4f;
// To minimize lag time before start of output, preload buffers
[player prepareToPlay];
// Play the sound once (set negative to loop)
[player setNumberOfLoops:0];
[player play];
}
...
// Cleanup
if (player != nil)
{
if (player.isPlaying == YES)
[player stop];
[player release];
}
Related posts:
- Playing Sounds/Audio – Audio Session Services
- Silent Mode Switch and Playing Sounds
- iPhone File System: Creating, Renaming and Deleting Files
- Write Debug Output to a File
- Get Users Home Directory – Part 2
Comments
2 Responses to “Playing Sounds/Audio – AVAudioPlayer”
Leave Comment
Great! :)
[Reply]
Thank you so much..
[Reply]