【问题标题】:Audio player works in simulator but not on iOS device音频播放器在模拟器上工作,但在 iOS 设备上不工作
【发布时间】:2016-06-02 04:32:32
【问题描述】:

我有以下代码初始化:

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

然后一个按钮启动播放器

[_audioPlayer play];

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

【问题讨论】:

    标签: ios objective-c avaudioplayer audio-player


    【解决方案1】:

    在你的 app bundle 中获取文件路径的正确方法是这样的:

    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);
    }
    

    【讨论】:

    • 什么也没做
    • 什么没有?我提出了很多建议。你做了我建议的一切吗?请具体。
    • 很抱歉,我收回了。原来我设备上的扬声器有问题。我通过辅助电缆播放它,它起作用了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多