Play sound in iOS apps: AudioToolbox
How to play (short) sounds in iOS apps…
The max length of the sound is 30”. Don’t forget this.
Well, suppose that you have a “backtothefuture.mp3” file into the iOS app project.
Now you can follow this simple steps:
1. add the AudioToolbox.framework
2. import the AudioToolbox.framework writing
#import <AudioToolbox/AudioToolbox.h>
3. write the code for create, play and dispose the sound using the AudioServices classes
+(void)playSound
{
NSString *songName = @"backtothefuture.mp3";
SystemSoundID mSound;
NSString* path = [[NSBundle mainBundle]
pathForResource:songName ofType:nil];
NSURL* url = [NSURL fileURLWithPath:path];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mSound);
// Sounds played with AudioServicesPlaySystemSound can not be longer then 30 secs.
// So we can dispose the system sound id after that period.
AudioServicesAddSystemSoundCompletion(mSound, NULL, NULL, systemAudioCallback, NULL);
AudioServicesPlaySystemSound(mSound);
}
//it is a function, not a method! This function is called when the sound stops to play
void systemAudioCallback(SystemSoundID soundId, void *clientData)
{
AudioServicesDisposeSystemSoundID(soundId);
}
4. finally call the class method writing [MySoundClass playSound];
That’s all!
1 nota




