[英]Audio player works in simulator but not on iOS device
I have the following code initializing: 我有以下代码初始化:
NSString *path = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
Then a button starts the player 然后一个按钮启动播放器
[_audioPlayer play];
So it works fine when I am on the simulator but it doesn't work on my device. 因此,当我在模拟器上时,它工作正常,但在我的设备上不起作用。
The proper way to get the path of a file in your app bundle is like this: 在您的应用包中获取文件路径的正确方法如下:
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
But if you actually want an NSURL
, use the following to get it directly: 但是,如果您实际上想要一个NSURL
,请使用以下代码直接获取它:
NSURL *soundUrl = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"mp3"];
Also, the simulator isn't case sensitive but a real device is. 而且,模拟器不区分大小写,但实际设备却区分大小写。 Make sure your file is really named test.mp3
and not something like Test.mp3
. 确保您的文件的名称真实为test.mp3
而不是Test.mp3
类的Test.mp3
。 Update the name in the code to match the actual filename. 更新代码中的名称以匹配实际的文件名。
Use the debugger to make sure that soundURL
isn't nil
. 使用调试器确保soundURL
不为nil
。 If not but the audio player still doesn't work, use the error
parameter to see why: 如果不是,但是音频播放器仍然无法工作,请使用error
参数查看原因:
NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (!_audioPlayer) {
NSLog(@"Unable to create audio player: %@", error);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.