不使用AVAudioPlayer播放mp3文件

时间:2016-06-03 04:33:35

标签: ios objective-c avaudioplayer avaudiosession

我想用AVAudioPlayer播放歌曲。但是这段时间不起作用。我没有得到什么问题。 我正在使用下面的代码从本地播放mp3文件。

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])这种情况永远不会让人满意,为什么会这样,请帮我解决这个问题。

我得到以下错误: 的 Error:Error Domain=NSOSStatusErrorDomain Code=560557684 "The operation couldn’t be completed. (OSStatus error 560557684.)" 提前致谢

1 个答案:

答案 0 :(得分:1)

这是解决方案,它完美无缺:)

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