Play Audio iOS Objective-C

Maybe you should try using the NSBundle method pathForResource:ofType: method to create the path to the file.

The following code should successfully play an audio file. I have only used it with an mp3, but I imagine it should also work with m4a. If this code does not work, you could try changing the format of the audio file. For this code, the audio file is located in the main project directory.

/* 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];

EDIT

Ok, so try this:

NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.m4a",[[NSBundle mainBundle] resourcePath]];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

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

[player play];

Also, make sure you do the proper imports:

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

Leave a Comment