Domanda

My iOS app wants to play a local audio file. So, in xCode, I’ve added a file "audio.m4a" to my project. It resides on the top level of the file tree, but

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

returns nil. There must be a stupid oversight. What am I doing wrong?

È stato utile?

Soluzione

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

and check whether that file present in Build Phases" -> "copy bundle Resources"

Altri suggerimenti

Swift

Since neither answer is complete, and the solution is disseminated in the comments, let me offer a Swift alternative. and a step-by-step response.

The original Objective-C code is correct:

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

Swift

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

Target Membership

This was probably an oversight when originally adding the resource to the project. You must select adequate targets when adding these files:

Add to targets

Regardless of the language, ensure that your file is Project > Build Phases > Copy Bundle Resources. You need not to do that by hand. Instead, use the File Inspector. Select your resource (on the left panel) and verify it's target membership (on the right panel):

Target Membership

/* 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];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top