简体   繁体   中英

Does not play mp3 file using AVAudioPlayer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM