输入背景时出现AVAudioSession问题

时间:2015-01-15 19:21:02

标签: ios objective-c iphone sprite-kit avaudiosession

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

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中有两个公共方法来停止和播放我的音乐:

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

    [self.backgroundMusicPlayer play];
}

这是我在进入后台之前从appDelegate.m做的事情,我从viewController调用方法停止音乐,然后停止AVAUdioSession

    - (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

任何帮助都会被贬低,谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

其中audioPlayer是我班级标题中声明的变量。

指令prepareToPlay应解决您的问题!

这可能对您有所帮助:)。

相关问题