【问题标题】:Playing a sequence of audio files in background在后台播放一系列音频文件
【发布时间】:2012-04-15 11:59:25
【问题描述】:

在我的应用程序中,我有一个 AVAudioPlayer 实例,它播放一系列 mp3,通过initWithData 切换到下一个:

我想让用户即使关闭屏幕或进入后台也能继续收听播放器。我知道,当用户点击它时,我可以使用remotecontrolevents 切换到其他音频,但我可以让它自动切换,就像在 iPod 播放器中一样?

【问题讨论】:

  • 你的意思是当前曲目完成后?
  • 是的,我将音频文件的 URL 存储在核心数据对象中

标签: objective-c ios background avfoundation avaudioplayer


【解决方案1】:

您需要使用AVAudioPlayerDelegate 协议。首先将其包含在您的界面中:

@interface MyAppViewController : UIViewController <AVAudioPlayerDelegate> {
    AVAudioPlayer   *yourPlayer;
}

@property (nonatomic, retain) AVAudioPlayer *yourPlayer;

然后在你的实现中:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//This method is called once the file has finished playing
//Insert code here to play the next file
}

不要忘记在您的 viewDidLoad 方法(或您决定放置的任何位置)中将 yourPlayerdelegate 设置为 self

- (void)viewDidLoad {
    [super viewDidLoad]

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

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
    }

    self.yourPlayer = [[AVAudioPlayer alloc] init];
    self.yourPlayer.delegate = self;
}

您还需要将 info.plist 中的所需背景模式更改为 应用播放音频

不要忘记取消注册远程控制事件(viewDidUnload):

[[UIApplication sharedApplication] endReceivingRemoteControlEvents]

【讨论】:

  • 你确定,如果我在后台并且可以访问那里的托管对象,didFinishPlaying 会被调用吗?
  • audioPlayerDidFinishPlaying 将在后台调用,前提是您在 .plist 文件中设置上述模式,同时调用 beginReceivingRemoteControlEvents(注意,有些可能会将音频会话初始化和远程控制事件放入viewDidAppear)。有一个线程 here 提供更多信息。
  • 在模拟器 vut 上效果很好,所以在真实设备上根本不工作——你不知道为什么会这样吗?
  • 在设备上测试有什么问题?
  • 它只是停止播放,无论我是转到主屏幕还是关闭屏幕。也许我必须在一些 plist 中添加更多内容?
猜你喜欢
  • 1970-01-01
  • 2016-12-18
  • 2011-03-18
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多