使用AVAudioPlayer播放的MP3无法在设备上运行

时间:2011-01-09 18:21:00

标签: iphone iphone-sdk-3.0 ios4 avaudioplayer

我正在使用iOS 4.2在我的3GS iPhone上测试我的应用程序

我正在使用以下代码在我的IBAction中播放声音。它在模拟器(iPad和iPhone)中完美运行 - 我听到了声音。

NSString *pathToMusicFile1 = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"mp3"];
NSError *error;
alarmSound = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile1] error:&error]; 
NSLog(@"Song1 Loaded");
if (alarmSound == nil) {
    NSLog(@"Error playing sound");
} else {
    alarmSound.numberOfLoops = 20;
    alarmSound.volume = 1.0;
    [alarmSound play];
}

我可以正确地声明所有内容(标题和框架等),因为我可以在模拟器中听到声音。

我还检查过我的手机没有处于静音模式!我听到了通用iphone GUI的其他声音。 (来自日期选择器的例子)。

我还清理了所有目标并删除了应用以重新安装。

任何想法有什么不对?!

4 个答案:

答案 0 :(得分:49)

所以,我也有这个问题 - 我很确定它是同一个......

我们已经在应用程序商店中安装了一年左右的应用程序,最近我们需要更改一些内容,尽管没有任何功能。

突然,声音停止工作 - 最新的sdk版本(版本4.0)和设备上的模拟器(再次运行iOS 4)。

始终为我们工作的代码是......

NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"track1" ofType:@"mp3"])){

NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
audioPlayer.delegate = self;
[url release];

[audioPlayer prepareToPlay];
[audioPlayer play];

}

最后,我发现您现在需要设置AVAudioSession播放的类型,以便通过扬声器播放声音,就像它已经做到的那样!在您的app appate applicationDidFinishLaunching事件处理程序...

中放入以下代码行
- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

不要忘记在app delegate .h文件中添加include(显然你还需要导入AVFoundation框架,如果还没有这样做的话)...

#import <AVFoundation/AVAudioSession.h>

希望这会让你的声音在设备上播放。

不要因为我认为可能是一个单独的问题而变得明白,那声音仍然无法在模拟器中播放。我见过其他帖子暗示这是事实,但我不确定这是多么普遍。我发现如果我选择iPad 3.2作为我的模拟器,它至少可以解决这个问题。快乐!

对我来说似乎很疯狂的是,这肯定会影响到很多人,但很难找到关于某些应该是一个众所周知的问题的信息或建议 - 毕竟,我已经看到很多帖子在似乎没有得到答复的论坛上。

无论如何,希望这有助于其他人。

答案 1 :(得分:26)

拥有&#34; audioPlayer&#34; 非常重要变量作为属性。否则使用ARC,它会在有机会玩之前释放!

我花了半个小时和一些谷歌搜索这个A-ha时刻。

我的声音现在完美无缺!

答案 2 :(得分:17)

我的问题是iOS在文件有机会播放之前自动释放我的AVAudioPlayer实例。奇怪的是,这只发生在MP3而非AU文件中。解决方法是不将其设置为自动释放,然后在委托方法中释放它...

- (void)playSound:(NSString *)sound
{
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sound ofType:@""]] error:NULL];
    audioPlayer.delegate = self;
    [audioPlayer play];
}

...然后在委托方法中......

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player release];
}

......现在效果很好。

答案 3 :(得分:1)

您是否尝试过[NSURL URLWithString:pathToMusicFile1];而不是fileURLWithPath: