簡體   English   中英

進入后台時出現AVAudioSession問題

[英]AVAudioSession issue when entering background

我試圖在音樂進入背景之前停止音樂播放器,但沒有成功。 我查看了所有具有相同問題的問題,但找不到所需的答案。 我正在從主View Controller播放游戲音樂:

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

任何幫助將不勝感激,謝謝!

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

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

其中audioPlayer是在我的類的標題中聲明的變量。

指令prepareToPlay應該可以解決您的問題!

這可能會幫助您:)

暫無
暫無

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

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