Signo Signo - 1 year ago 138
Objective-C Question

Play simple sound

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.
I've added

as framework and this is the code I tried to use:

SystemSoundID playSoundID;
NSURL *clockSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"clock" ofType:@"mp3"]]; //the path for my resource
AudioServicesCreateSystemSoundID((__bridge CFURLRef)clockSound, &playSoundID);

I don't get any errors but the sound isn't played

Answer Source

AudioServicesPlaySystemSound() function cannot play any MP3 files. The function supports only these file formats that are .caf, .aac, or .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.

To convert mp3 to 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 AVPlayer of 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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download