I can not play mp3 file using AVAudioPlayer

I want to play mp3 file hosted in resources as 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 can't hear the sound please help

+3
source share
3 answers

I do not think your file name is correct. Try this syntax:

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

I had a similar problem due to ARC. Instead of defining AVAudioPlayer in the same method that you use, you should have an instance variable somewhere else, such as a UIViewController. Therefore, ARC does not automatically release this object, and sound can be played.

+2
source
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 the answer

+1
source

Source: https://habr.com/ru/post/1783558/


All Articles