AVAudio背景音乐没有停顿

时间:2013-05-01 20:34:32

标签: ios objective-c avaudioplayer multitasking

对于我正在使用的音频

- (void)viewDidLoad {

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"Music" ofType: @"m4a"];

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

    AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
    self.audioPlayer = newPlayer;
    [newPlayer release];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    if (self.audioPlayer) {
        [self updateViewForPlayerInfo];
        [self updateViewForPlayerState];
        [self.audioPlayer setDelegate:self];
                           }

    [fileURL release];
    [super viewDidLoad];

                    }

和plist“App播放音频”设置,
按下主页时会播放背景声音,但多任务切换器或锁定屏幕的遥控器不起作用,背景音频无法暂停或转发/重新播放。

怎么了?

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要添加一些内容才能接收这些事件调用。

在视图控制器中添加

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
    return YES;
}

在你的app delegate add

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {

        case UIEventSubtypeRemoteControlTogglePlayPause:
            //handle play button
            break;

        case UIEventSubtypeRemoteControlPreviousTrack:
            //handle rew button
            break;

        case UIEventSubtypeRemoteControlNextTrack:
            //handle ff button
            break;

        default:
            break;
        }
    }
}