使用AVAudioplayer在后台播放音乐

即使应用程序在后台运行,我也想播放音乐。我检查了所有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];


牛魔王的故事
浏览 1197回答 3
3回答

守着星空守着你

我已经通过引用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];}

qq_花开花谢_0

我只想在Mehul的答案中添加注释。这行:[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];实际上非常重要。我使用其他教程来启动和运行我的AVAudioPlayer。一切正常,但如果应用程序在后台运行,我的音频将无法启动。需要澄清的是,当应用程序进入后台时,如果已经在播放我的音频,那很好。但是如果应用程序已经在后台,则无法开始播放。添加上面的代码行即可,即使应用程序处于后台,我的音频也将开始播放。
打开App,查看更多内容
随时随地看视频慕课网APP