What's the SIMPLEST way to play a sound clip in an iPhone app?

只愿长相守 提交于 2019-12-03 09:48:52

Apple has an article on this subject, see: this link

AVAudioPlayer is the simplest way to play sounds of any length, looping or not, however it requires iPhone OS 2.2 or higher. A simple example:

NSString *soundFilePath =
                [[NSBundle mainBundle] pathForResource: @"sound"
                                                ofType: @"wav"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

AVAudioPlayer *newPlayer =
                [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
                                                       error: nil];
[fileURL release];

[newPlayer play];

[newPlayer release];

It will play virtually any file format (aiff,wav,mp3,aac) Keep in mind that you can only play one mp3/aac file at a time.

Here's the simplest way I know of:

  1. Convert your sound file to caf (use afconvert commandline tool) and add to your project.

    caf stands for Core Audio Format (I think...)

  2. Look for SoundEffect.h and .m in Apple's sample code. I believe both Metronome and BubbleLevel have it.

  3. Copy to your project
  4. Write code like below:

    SoundEffect *SimpleSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:@"soundfile" ofType:@"caf"]];
    [SimpleSound play];
    [SimpleSound release];
    

Study SoundEffect.m to get an idea of simple sound handling.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!