Search code examples
iphonemp3avfoundationcore-audio

I can not play mp3 file using AVAudioPlayer


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


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