如何从iPhone应用程序停止和恢复背景音频?

时间:2012-09-18 10:21:40

标签: ios objective-c audio avaudioplayer resume

我在基于Messaging的iPhone应用程序中工作。我添加了Beep声音以接收来自其他人的消息。我正在使用AVAudioPlayer播放哔声。我的问题是当用户在后台从其他应用程序听到歌曲时,如果他们从我的应用程序接收到消息,则将发出哔声并且后台歌曲/音频停止不恢复。

我希望通过暂停背景歌曲/音频播放我的哔声,然后我必须从我的应用程序中恢复该音频/歌曲。在iOS开发中有可能吗?有人可以帮帮我吗?

编辑:

这是我的示例代码。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Music";
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

    NSString *urlString = [[NSBundle mainBundle] pathForResource:@"basicsound" ofType:@"wav"];
    NSURL *audioURL = [[NSURL alloc] initWithString:urlString];
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
    [audioPlayer setDelegate:self];
    [audioPlayer prepareToPlay];

    audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:YES error:&error];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    [audioPlayer play];    
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (flag == YES) 
    {
        NSLog(@"Audio Played successfully");
        NSError *error;
        [audioSession setActive:NO error:&error];
    }
}

2 个答案:

答案 0 :(得分:14)

派对有点晚了,但是对于那些在播放声音后寻找解决暂停和取消暂停背景(即ipod音乐)问题的人,你应该在停用音频会话时使用以下内容。

[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

//未弃用的新方法:

[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&error];

每当您在应用程序中不需要音频会话时(即,当您没有输出任何声音时),您应该停用它。在有意义的地方,您应该使用此方法,以便通知任何背景音频并可以恢复(接收此通知的应用程序不一定必须恢复)。

此外,您必须使用适当的音频类别,以便在需要时专门播放您的声音。这可以使用AVAudioSessionCategoryAmbient以外的任何类别来完成。当您的音频会话变为活动状态时,这将自动为您暂停背景音频。但是,它不会重新激活任何背景音频,这是通过使用上述代码完成的。在这种情况下,如前所述,背景音频然后决定如何处理通知。

旁注,另一个值得关注的选择是音频'躲避'。如果您的声音不是必须单独播放,例如简单的警报声,请尝试使用闪避降低背景音频的音量以播放您的声音,完成后将声音完成后将背景音频恢复正常播放。有关这些概念的详细信息,请参阅Configure your Audio Session

答案 1 :(得分:6)

您无法为所有应用程序执行此操作。对于在其应用程序中使用iPod播放器的应用程序:

假设您的应用程序位于前台。你可以这样做:

MPMusicPlayerController *mp = [MPMusicPlayerController iPodMusicPlayer];        
[mp stop]; // or [mp pause]

这需要MediaPlayer.framework#import <MediaPlayer/MediaPlayer.h>

MPMusicPlayerController Reference了解详情。


要通过音频播放器会话执行此操作,您可以使用属性kAudioSessionCategory_SoloAmbientSoundReference here

这类似于AVAudioSession class中定义的AVAudioSessionCategorySoloAmbient

从文档中引用:

  

当您使用此类别时,其他应用的音频会被静音。

相关问题