I want to play song using AVAudioPlayer. But this is does not work some time. I did not get what is the issue. I'm using this below code to play mp3 file from local.
NSString *soundFile;
soundFile = [[NSBundle mainBundle] pathForResource:@"notification_sound" ofType:@"mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:soundFile];
NSError *error=nil;
self.playerAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive: YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.playerAudio setDelegate:self];
NSLog(@"Error:%@",error);
self.playerAudio.numberOfLoops = -1;
self.playerAudio.volume=1;
if([self.playerAudio prepareToPlay])
{
NSLog(@"Prepare to play successfully");
[self.playerAudio play];
}
if([self.playerAudio prepareToPlay])
this condition never be satisfied why this is happened please help me to solved this issue.
I got this below error :
Error:Error Domain=NSOSStatusErrorDomain Code=560557684 "The operation couldn’t be completed. (OSStatus error 560557684.)"
Thanks in advance
This is the solution and it is works perfectly :)
NSError *error=nil,*sessionError = nil;
NSString * soundFile = [[NSBundle mainBundle] pathForResource:@"notification_sound" ofType:@"mp3"];
NSURL *fileURL = [NSURL fileURLWithPath:soundFile];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
withOptions:AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDuckOthers
error:&sessionError];
if (sessionError) {
NSLog(@"ERROR: setCategory %@", [sessionError localizedDescription]);
}
[[AVAudioSession sharedInstance] setActive: YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
self.playerAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
[[AVAudioSession sharedInstance] setActive: YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.playerAudio setDelegate:self];
self.playerAudio.numberOfLoops = -1;
self.playerAudio.volume=1;
if([self.playerAudio prepareToPlay])
{
[self.playerAudio play];
}