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

标签 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];

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

最佳答案

在您的应用程序捆绑包中获取文件路径的正确方法如下:

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/

相关文章:

c# - Xamarin iOS - 如何在绑定(bind)库时包含依赖项?

ios - 播放和暂停功能

swift - 如何快速制作音频播放器?

ios - 当 View Controller 出现时如何在 viewWillAppear 中获取 View Controller 的框架使用 UIModalPresentationFormSheet

ios - 如何在 Xcode 6 中使用约束来正确调整对象的大小?

ios - 使用 UITableView 和数组无限滚动

objective-c - Cocoa的TextField返回 Action 控制

ios - iOS 是否支持可跨越的字符串?

iphone - 制作自定义类的按钮触发父类

arrays - 从iPhone库歌曲中获取阵列中的原始样本