Question

I want to play mp3 file placed in resources as code is given below,

NSString *st=@"alarm_1.mp3";
NSLog(st);
NSURL* musicFile = [NSURL fileURLWithPath:st]; 

AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];

//AVAudioPlayer *click1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:@"alarm_1.mp3"]];

[click prepareToPlay];
[click play];
[click release];

but unfortunately i cant hear the sound please help

Was it helpful?

Solution

I don't think your file name is right. Try this syntax:

    NSURL *clickURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/alarm_1.mp3", [[NSBundle mainBundle] resourcePath]]];  
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:clickURL error:nil];

OTHER TIPS

I had a similar problem due to ARC. Instead of defining the AVAudioPlayer in the same method you are using it, you should should have an instance variable somewhere else, such as the UIViewController. This way ARC doesn't auto release this object and audio can play.

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/alarm_1.mp3", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;

[audioPlayer play]; 

This is answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top