使用 AVAudioplayer 在后台播放音乐 [英] Play music in the background using AVAudioplayer

查看:40
本文介绍了使用 AVAudioplayer 在后台播放音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使应用程序进入后台,我也想播放音乐.我检查了所有 stackoverflow 链接,但没有一个有效.请帮助今天需要做的事情.

I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.

我使用了以下代码:-

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];

推荐答案

我通过参考 iOS应用后台任务

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

and make some changes in .plist file of our application..

更新

在您的控制器视图中编写此代码确实像这样加载方法

write this code in your controller's view did load method like this

- (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];
}

这篇关于使用 AVAudioplayer 在后台播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆