为了账号安全,请及时绑定邮箱和手机立即绑定

使用AVAudioplayer在后台播放音乐

使用AVAudioplayer在后台播放音乐

牛魔王的故事 2019-10-18 09:57:38
即使应用程序在后台运行,我也想播放音乐。我检查了所有stackoverflow链接,但没有一个起作用。请帮忙今天做。我使用了以下代码:-NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Day At The Beach"  ofType: @"mp3"];NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];NSError *error;playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];playerTemp.numberOfLoops = 0;AudioSessionSetActive(true);[playerTemp play];
查看完整描述

3 回答

?
守着星空守着你

TA贡献1799条经验 获得超8个赞

我已经通过引用iOS应用程序后台任务解决了这个问题


并在.plist我们的应用程序文件中进行一些更改。


更新资料


在控制器的视图中编写此代码,是否执行了像这样的加载方法


- (void)viewDidLoad

{

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"in-the-storm" ofType:@"mp3"]];

    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

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

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

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    [audioPlayer play];

    [super viewDidLoad];

}


查看完整回答
反对 回复 2019-10-18
?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

我只想在Mehul的答案中添加注释。这行:


[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

实际上非常重要。我使用其他教程来启动和运行我的AVAudioPlayer。一切正常,但如果应用程序在后台运行,我的音频将无法启动。需要澄清的是,当应用程序进入后台时,如果已经在播放我的音频,那很好。但是如果应用程序已经在后台,则无法开始播放。


添加上面的代码行即可,即使应用程序处于后台,我的音频也将开始播放。


查看完整回答
反对 回复 2019-10-18
  • 3 回答
  • 0 关注
  • 1192 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信