Kyle Griffith Kyle Griffith - 1 year ago 60
Objective-C Question

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 *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. Update the name in the code to match the actual filename.

Use the debugger to make sure that soundURL isn't nil. If not but the audio player still doesn't work, use the error parameter to see why:

NSError *error = nil;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
if (!_audioPlayer) {
    NSLog(@"Unable to create audio player: %@", error);