我有以下代码初始化:
NSString *path = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
然后一个按钮启动播放器
[_audioPlayer play];
因此,当我在模拟器上时,它工作正常,但在我的设备上不起作用。
最佳答案
在您的应用程序捆绑包中获取文件路径的正确方法如下:
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);
}
关于ios - 音频播放器可在模拟器中工作,但不能在iOS设备上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37582712/