进入后台时AVAudioSession问题

AVAudioSession issue when entering background

我试图在我的游戏进入后台之前停止音乐播放器,但没有成功。我查看了所有与我遇到的问题相同的问题,但找不到我需要的答案。我正在从主视图控制器播放我的游戏音乐:

XYZViewController.h

@import AVFoundation;

@interface XYZViewController : UIViewController 
@property (readwrite)AVAudioPlayer* backgroundMusicPlayer;

编辑添加这段代码,这是我分配和初始化音乐播放器。忘记了,补充之前,抱歉:

XYZViewController.m
- (void)viewDidLoad
{

    [super viewDidLoad];
    [self gameCenterLogin];

    // Configure the view.
    SKView * skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;


    //AUDIO BACKground
    NSError *error;
    NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"Astro World music" withExtension:@"mp3"];
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    self.backgroundMusicPlayer.numberOfLoops = -1;
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];

[skView presentScene:scene];

}

我的 viewController 中有这两个 public 方法来停止和播放我的音乐:

-(void)stopPlayer{
    [self.backgroundMusicPlayer stop];
}
-(void)playMusic{

    [self.backgroundMusicPlayer play];
}

这是我在 appDelegate.m 进入后台之前所做的,我在停止 AVAUdioSession

之前从我的 viewController 调用方法来停止音乐
    - (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.


    XYZViewController* mainController = (XYZViewController*)  self.window.rootViewController;
    [mainController stopPlayer];
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
    NSLog(@"pause music");

}

但是无论我做什么我总是得到同样的错误:

    RROR:     [0x35aa49dc] AVAudioSession.mm:646: -[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.
2015-01-15 20:09:49.080 Astro World[269:23154] pause music

任何帮助将不胜感激,谢谢!

将此代码插入 AVAudioPlayerDelegate 的方法中。

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
  [audioPlayer stop];
  [audioPlayer prepareToPlay];
}

其中 audioPlayer 是在我的 class 的 header 中声明的变量。

prepareToPlay 指令应该可以解决您的问题!

这可能对你有帮助:)