ユーザーが 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)
}
});
}