在iPhone应用中播放音频片段的最简单方法是什么?

3

我希望能在iPhone OS应用程序中播放音频剪辑。我看到过关于使用NSSoundAVFoundation的信息,这些都是在iPhone OS设备上播放音频剪辑的方法,但是我仍然不清楚这个主题,需要一些帮助。不需要为我逐步解释实际代码,但如果有人能给我一个提示,指出我应该开始移动的一般方向(即我应该关注哪些类),那么我自己就可以填补空白。那么,在iPhone应用程序中播放音频剪辑的最简单方法是什么?

2个回答

8
苹果公司在这个主题上有一篇文章,请查看:此链接 AVAudioPlayer是播放任何长度的声音,循环或非循环的最简单方法,但需要iPhone OS 2.2或更高版本。一个简单的例子:
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];

它可以播放几乎任何文件格式(aiff,wav,mp3,aac)。请记住,您一次只能播放一个mp3 / aac 文件。


不确定iOS 2.2及以下版本,但使用多个AVAudioPlayer实例可以完全同时播放多个mp3。 - Jonny
尝试播放后立即释放播放器可能会导致问题。 - Rizon

6

以下是我所知道的最简单的方法:

  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];
    

学习SoundEffect.m可以了解简单的声音处理。


刚刚实现了这个,效果很好!只需要使用Audacity将wav文件转换为另一个wav格式,afconvert就能正常运行了,没有其他问题。 - JOM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接