如果用户在播放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)
}
});
}
答案 0 :(得分:0)
首先,myAudioPlayer是Page1ViewController的一个属性,但在你的AppDelegate中,你引用它就像在委托中声明它一样。
你应该获得对Page1ViewControllers音频播放器的引用停止。
除非我误解了你的代码,否则你应该做这样的事情。
- (void)applicationWillEnterForeground:(UIApplication *)application {
......
[self.page1ViewController.myAudioPlayer stop];
......
}
答案 1 :(得分:0)
或者,如果您不想创建Page1ViewController的属性,可以在Page1ViewController中创建一个方法,该方法返回myAudioPlayer以在另一个类(如AppDelegate)中使用。以下示例..
//Page1ViewController.h
@interface Page1ViewController : UIViewController...
....
-(AVAduioPlayer*)currentPlayer;
@end
//Page1ViewController.m
-(AVAudioPlayer*)currentPlayer {
return self.myAudioPlayer;
}
//AppDelegate.m
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[page1ViewController currentPlayer] stop];
}