音频播放器可在模拟器中运行,但不适用于iOS设备

时间:2016-06-02 04:32:32

标签: ios objective-c avaudioplayer audio-player

我有以下代码初始化:

NSString *path = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

然后按钮启动播放器

[_audioPlayer play];

所以当我在模拟器上时它工作正常,但它在我的设备上不起作用。

1 个答案:

答案 0 :(得分:4)

在应用包中获取文件路径的正确方法如下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];

但如果你真的想要一个NSURL,请使用以下内容直接获取它:

NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"mp3"];

此外,模拟器不区分大小写,但真正的设备是。确保您的文件名为test.mp3,而不是Test.mp3。更新代码中的名称以匹配实际文件名。

使用调试器确保soundURL不是nil。如果没有,但音频播放器仍无法正常工作,请使用error参数查看原因:

NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (!_audioPlayer) {
    NSLog(@"Unable to create audio player: %@", error);
}
相关问题