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

Mat*_*cer 19 iphone avaudioplayer iphone-sdk-3.0 ios4

我在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];
}
Run Code Online (Sandbox Code Playgroud)

我已经将所有声明正确(标题和框架等),因为我可以在模拟器中听到声音.

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

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

有什么想法有什么不对?!

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

}
Run Code Online (Sandbox Code Playgroud)

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

- (void)applicationDidFinishLaunching:(UIApplication *)application {

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Run Code Online (Sandbox Code Playgroud)

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

#import <AVFoundation/AVAudioSession.h>
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 代码`[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];`只是覆盖静音开关,让你在手机锁定AFAIK时播放声音. (4认同)

Anj*_*aan 26

这是极为重要的有"audioPlayer"变量作为属性.否则使用ARC,它会在有机会玩之前释放!

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

我的声音现在完美无缺!

  • 经过一个小时的头撞,我终于找到了这个帖子.谢谢. (5认同)

rob*_*408 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];
}
Run Code Online (Sandbox Code Playgroud)

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

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player release];
}
Run Code Online (Sandbox Code Playgroud)

......现在很棒.

  • ARC在播放之前释放了播放器.将播放器设置为属性为我解决了这个问题. (19认同)

小智 1

你尝试过[NSURL URLWithString:pathToMusicFile1];而不是吗fileURLWithPath: