在Iphone上播放声音的最简单方法是什么?

时间:2012-08-26 15:46:17

标签: iphone

在Iphone上播放声音的最简单方法是什么?我有一个mp3文件,我宁愿保留它,也不要将其转换为其他格式。

3 个答案:

答案 0 :(得分:3)

我知道播放MP3文件的最简单方法是使用AVAudioPlayer类。基本上,只需执行(跳过错误检查,设置代理以检测完成等):

NSURL* soundUrl = [[NSBundle mainBundle] URLForResource:@"soundFile" withExtension:@"mp3"];
AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&err];
[player play];

答案 1 :(得分:1)

首先将AVFoundation Framework添加到项目中[Goto Target>右键单击项目> Build Phases> Link Binary with Library>点击+>选择AVFoundation>添加]

// get file path
NSString *soundPath = [[NSBundle mainBundle] pathForResource: fileNameToPlay ofType:@"mp3"];

// allocate and refer to file
AVAudioPlayer *player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: soundPath] error: NULL];

// set delegate
player. delegate = self; 

// play
[player play];

答案 2 :(得分:0)

显然,事实证明这很糟糕,但我找到了一个解决方案。我正在运行XCode 4.4.1。

以下是对我有用的步骤:

  1. 将mp3文件从finder拖到XCode项目中 - >支持文件。确保复制该文件。我们假设文件名是sound.mp3。
  2. 将AVFoundation框架添加到您的项目中。
  3. import< AVFoundation / AVFoundation.h>

  4. @property(强)AVAudioPlayer * soundPlayer;
  5. 使用以下代码初始化播放器并播放mp3: NSURL * chemin = [NSURL fileURLWithPath:[NSString stringWithFormat:@“%@ / sound.mp3”,[[NSBundle mainBundle] resourcePath]]]; NSError *错误; self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:chemin error:& error]; [self.soundPlayer play];
  6. 现在,我得到了一个例外情况,在此处描述:AVFoundation iOS 5 简而言之,这意味着模拟器中可能存在一个不应该在设备上发生的错误。在我的情况下,我打开了所有异常,这阻止了我的代码执行。你应该做的是删除抛出所有异常的选项。

    另外,在我的情况下,它首先播放声音需要3-5秒,所以当你没有立即听到声音时请耐心等待。在它第一次播放后,它会立即播放。