1

我的 iOS 应用想要播放本地音频文件。所以,在 xCode 中,我在我的项目中添加了一个文件“audio.m4a”。它位于文件树的顶层,但

    NSURL *audioFileURL = [[NSBundle mainBundle] 
URLForResource:@"audio" 
withExtension:@"m4a"];

返回nil。一定有一个愚蠢的疏忽。我究竟做错了什么?

4

3 回答 3

4
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: @"audio" ofType: @"m4a"];
NSURL *audioFileURL = [NSURL URLWithString:myFile];

并检查该文件是否存在于Build Phases" -> "copy bundle Resources"

于 2013-10-04T12:39:40.950 回答
1

迅速

由于这两个答案都不完整,并且解决方案已在评论中传播,因此让我提供一个Swift替代方案。和一步一步的回应。

原始的Objective-C代码是正确的:

NSURL *audioFileURL = [[NSBundle mainBundle] 
    URLForResource:@"audio" 
    withExtension:@"m4a"];

迅速

let audioFileURL = NSBundle.mainBundle().URLForResource(
    "audio",
    withExtension: "m4a")

目标会员

这可能是最初将资源添加到项目时的疏忽。添加这些文件时,您必须选择足够的目标:

添加到目标

无论使用哪种语言,请确保您的文件是Project > Build Phases > Copy Bundle Resources。您无需手动执行此操作。相反,请使用文件检查器。选择您的资源(在左侧面板上)并验证它的目标成员资格(在右侧面板上):

目标会员

于 2015-09-23T22:35:10.240 回答
0
/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite

[player play];
于 2013-10-04T12:39:17.820 回答