I need to play a sound when an action takes place, I already have the callback when the action ends and it's working fine and now I want to add a sound to it.
NSURL *clockSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"clock" ofType:@"mp3"]]; //the path for my resource
AudioServicesCreateSystemSoundID((__bridge CFURLRef)clockSound, &playSoundID);
AudioServicesPlaySystemSound() function cannot play any MP3 files. The function supports only these file formats that are
.wav and the sound must be 30 seconds or less.
Sound files that you play using this function must be: No longer than 30 seconds in duration In linear PCM or IMA4 (IMA/ADPCM) format Packaged in a .caf, .aif, or .wav file
So if the
clock.mp3 is less than 30 seconds in duration, you can play the sound if convert the file format.
caf, for example using
afconvert command, like below:
$ afconvert -f caff -d ima4 clock.mp3 clock.caf
If not (the sound is more than 30 seconds), use
AVFoundation.framework instead. See the link of The Senator's comment.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"m4a"]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; [player play];