如果用户在 iDevice 的音乐播放器播放时返回游戏,我想停止我的游戏音乐。
AppDelegate.m applicationWillEnterForeground 正在成功检查音乐播放器,但我不知道如何从这里告诉我的 AVAudioPlayer 停止。
真的很感激有人能告诉我怎么做吗?这让我非常头疼!
AppDelegate.m:
- (void)applicationWillEnterForeground:(UIApplication *)application
{
UInt32 propertySize, audioIsAlreadyPlaying=0;
propertySize = sizeof(UInt32);
AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &audioIsAlreadyPlaying);
if(audioIsAlreadyPlaying){¨
NSLog(@"iDevice Music is playing!");
[myAudioPlayer stop];//<<< *** the problemo bit *** :(
}
}
Page1ViewController.m 代码,以防万一:
- (void)viewDidLoad
{
NSError *myAudioSessionError = nil;
myAudioSession = [AVAudioSession sharedInstance];
if ([myAudioSession setCategory:AVAudioSessionCategoryAmbient error:&myAudioSessionError]){
NSLog(@"AVAudioSession created.");
}else {
NSLog(@"AVAudioSession not created.");
}
…
(if/else statements call the createAudioPlayer method.)
}
-(void)createAudioPlayer{
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void){
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *musicFilePath = [mainBundle pathForResource:@"main_music" ofType:@"aiff"];
NSData *musicFileData = [NSData dataWithContentsOfFile:musicFilePath];
NSError *myAudioPlayerError = nil;
//Start the audio player
self.myAudioPlayer = [[AVAudioPlayer alloc] initWithData:musicFileData error:&myAudioPlayerError];
if (self.myAudioPlayer != nil){//Check AVAudioPlayer successfully initiated
self.myAudioPlayer = self;
self.myAudioPlayer = -1;//loop continuously
if ([self.myAudioPlayer prepareToPlay]){
//(successfully created AudioPlayer)
}else {
//(failed to play)
}
}else {
//(failed to initiate an AudioPlayer)
}
});
}