0

如果用户在 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)
        }
    });
}
4

2 回答 2

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];
}
于 2012-06-03T13:48:29.847 回答
0

首先,myAudioPlayer 是 Page1ViewController 的一个属性,但在您的 AppDelegate 中,您引用它就像在委托中声明它一样。

您应该获得对 Page1ViewControllers 音频播放器的引用以停止。

除非我对您的代码有误解,否则您可能应该这样做。

- (void)applicationWillEnterForeground:(UIApplication *)application {

......

[self.page1ViewController.myAudioPlayer stop];

......



}
于 2012-06-03T13:25:24.990 回答