简体   繁体   English

音频播放器可在模拟器中工作,但不能在iOS设备上工作

[英]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.

相关问题 iOS Core Audio渲染回调只能在模拟器上使用,而不能在设备上使用 - iOS Core Audio render callback works on simulator, not on device 在iOS模拟器上可以使用,但在iOS设备上不能使用吗? - Works on iOS Simulator but not on iOS device? 音频播放器可以在后台的iOS模拟器上运行,但不能在iOS设备上使用(相同版本) - Audio player work on iOS simulator in Background but does not on iOS device (same version) iOS应用程序可在模拟器上运行,但不能在设备上运行 - IOS application works on the simulator but not on the device 字体适用于模拟器但不适用于 iOS 设备 - Font works on Simulator but not iOS device 目标C:音频在模拟器上有效,但在设备中无效 - Objective C: Audio works on simulator but not in device 背景音频在iOS模拟器上可运行,但不能在设备上运行 - background audio working on iOS simulator but not device 音频和振动在模拟器中工作,而不是在ios设备上 - Audio and vibrate working in simulator not on ios device iOS在模拟器上成功播放音频,但在设备上失败 - iOS play audio success on simulator but fail on device iOS 屏幕锁定时工作的音频播放器 - audio player that works when iOS screen is locked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM