簡體   English   中英

無法使用AVAudioPlayer播放mp3文件

[英]Does not play mp3 file using AVAudioPlayer

我想使用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.)"

這是解決方案,它可以完美地工作:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM