Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing sounds in iPhone SDK?

Does anyone have a snippet that uses the AudioToolBox framework that can be used to play a short sound? I would be grateful if you shared it with me and the rest of the community. Everywhere else I have looked doesn't seem to be too clear with their code.

Thanks!

like image 316
esqew Avatar asked Mar 20 '10 14:03

esqew


People also ask

How do I play custom Sounds on my iPhone?

Navigate to Settings -> Sounds on your iPhone or iPod touch (or, on your iPad, Settings -> General -> Sounds), and tap on the alert sound you wish to change. Now scroll to your newly-created sound—it'll be listed under the Ringtones section, but don't worry; you can use it for any of your alerts.

What is Avaudioplayer?

An object that plays audio data from a file or buffer.

How do I autoplay audio in iOS?

Tap the song that's playing at the bottom of your screen. In the lower-right corner of your screen, tap Playing Next. . Scroll down to Autoplay.


1 Answers

Here is an easy example using the AVAudioPlayer:

-(void)PlayClick
{
    NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                               pathForResource:@"click"
                                               ofType:@"caf"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click play];
    [click release];
}

This assumes a file called "click.caf" available in the main bundle. As I play this sound a lot, I actually keep it around to play it later instead of releasing it.

like image 129
Nathan S. Avatar answered Sep 21 '22 05:09

Nathan S.