如何让我的AVPlayer在应用程序在后台播放?

我已经完成了我的功课…一直在这里阅读,文档,谷歌search,stackoverflowing …但仍然没有运气让我的声音棒,当用户使应用程序进入后台。

到目前为止我所做的:将UIBackgroundModes,audio添加到plist文件。

首先这个代码:

radioAudio = [[AVAudioSession alloc] init]; [radioAudio setCategory:AVAudioSessionCategoryPlayback error:nil]; [radioAudio setActive:YES error:nil]; 

那么这个:

 NSString *radioURL = @"http://xxx.xxx.xxx/radio.m3u"; radioPlayer = [[AVPlayer playerWithURL:[NSURL URLWithString:radioURL]] retain]; 

但只要用户点击主页button,我的声音就会消失。

我也发现这个,但没有添加cuase一些我读过的东西说这是不需要的;

 newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask: bgTaskId]; bgTaskId = newTaskId; 

现在我不知道该怎么去让我的AVPlayer让广播歌曲,而用户在电话上做其他的东西。 我正在用4.2testingiPhone 4。 build设4.0。

任何人有什么build议我应该做的?

有同样的问题,但find了这个解决scheme..

看这里: https : //devforums.apple.com/message/395049#395049

以上链接的内容:


APPNAMEreplace为您自己的应用程序名称!

我在iOS 4.2.1上

编辑:到目前为止,使用iOS5 + 6 + 7testing版

APPNAME-Info.plist添加UIBackgroundModes ,selectApp播放audio

然后将AudioToolBox框架添加到文件夹框架。

APPNAMEAppDelegate.h添加:

 #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> 

所以它看起来像这样:

 ... #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> ... 

APPNAMEAppDelegate.m添加以下内容:

 // Set AudioSession NSError *sessionError = nil; [[AVAudioSession sharedInstance] setDelegate:self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError]; /* Pick any one of them */ // 1. Overriding the output audio route //UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; //AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride); // 2. Changing the default output audio route UInt32 doChangeDefaultRoute = 1; AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute); 

进入

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

但在两行之前:

 [self.window addSubview:viewController.view]; [self.window makeKeyAndVisible]; 

build立你的项目,看看是否有任何错误,如果没有,尝试模拟器上的设备insteddebugging,它可以在模拟器上的错误。

希望这可以帮助他人解决同样的问题

用Swift 4更新IOS 11.2:

现在,如果您使用AVPlayer播放音乐文件,则还应该configurationMPNowPlayingInfoCenter.default()以显示locking屏幕上正在播放的信息。

下面的代码将显示现在在屏幕上播放控件,但它将无法响应任何命令。

如果你还想控制工作,你应该在这里检查苹果的示例项目: https : //developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322

苹果示例代码涵盖了所有,但我觉得很困惑。

如果你想播放声音并在locking屏幕上显示控制,这些步骤将会很好。

重要提示:如果您使用AVPlayer播放声音。 如果您正在使用一些第三方库来生成声音或播放声音文件,则应该在代码中读取注释。 另外,如果您使用的是ios模拟器11.2,您将无法在locking屏幕上看到任何控件。 你应该使用一个设备来看看它的工作。


1-select项目 – > capabilites – >设置背景模式ON – >打勾audio,AirPlay和画中画

ios 11背景音频设置

2 – AppDelegate.swift文件应该是这样的:

 import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) //!! IMPORTANT !! /* If you're using 3rd party libraries to play sound or generate sound you should set sample rate manually here. Otherwise you wont be able to hear any sound when you lock screen */ //try AVAudioSession.sharedInstance().setPreferredSampleRate(4096) } catch { print(error) } // This will enable to show nowplaying controls on lock screen application.beginReceivingRemoteControlEvents() return true } } 

3- ViewController.swift应该如下所示:

 import UIKit import AVFoundation import MediaPlayer class ViewController: UIViewController { var player : AVPlayer = AVPlayer() override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "music", ofType: "mp3") let url = URL(fileURLWithPath: path!) // !! IMPORTANT !! /* If you are using 3rd party libraries to play sound or generate sound you should always setNowPlayingInfo before you create your player object. right: self.setNowPlayingInfo() let notAVPlayer = SomePlayer() wrong(You won't be able to see any controls on lock screen.): let notAVPlayer = SomePlayer() self.setNowPlayingInfo() */ self.setNowPlayingInfo() self.player = AVPlayer(url: url) } func setNowPlayingInfo() { let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default() var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]() let title = "title" let album = "album" let artworkData = Data() let image = UIImage(data: artworkData) ?? UIImage() let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_) -> UIImage in return image }) nowPlayingInfo[MPMediaItemPropertyTitle] = title nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo } @IBAction func startPlayingButtonPressed(_ sender: Any) { self.player.play() } 

老回答IOS 8.2:

帕特里克的回答是完全正确的。

但是我会写我为ios 8.2做的事情:

我添加我的应用程序的info.plist所需的背景模式,如下所示:

在这里输入图像说明

在我的AppDelegate.h我添加这些导入:

 #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> 

然后在我的AppDelegate.m我写应用程序didFinishLaunchingWithOptionsthis完全如下所示:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; return YES; } 

即使屏幕locking,现在应用程序仍然在播放音乐:)

我已经成功地使audio在后台运行,通过添加以下内容到我的applicationDidFinishLaunching

 // Registers this class as the delegate of the audio session. [[AVAudioSession sharedInstance] setDelegate: self]; // Allow the app sound to continue to play when the screen is locked. [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 

iOS 9 Swift

所有你需要的是添加以下到你的didFinishLaunchingWithOptions

 do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch { //TODO } 

你有一个GPS背景应用程序,即使在后台播放声音很好的例子:

http://www.informit.com/articles/article.aspx?p=1646438&seqNum=5

在这个例子中,使用AudioToolbox。

我做了一个testing我自己,它的工作原理:创build一个简单的项目,监测GPS的post( UIBackgroundModes location ),每接收到的位置,播放声音

AudioServicesPlaySystemSound(soundId);

然后,如果您将audio作为UIBackgroundModes一部分,即使应用程序不在前台,也会播放声音。

我已经做了这样的testing,它工作正常!

(我没有设法使它与AVPlayer,所以我fallbacked到AudioToolbox)

我遇到了同样的问题,我在Apple Docs中find了解决scheme: https : //developer.apple.com/library/ios/qa/qa1668/_index.html

问:我的应用程序在后台使用AV Foundation时,如何确保媒体能够继续播放?

答:您必须声明您的应用在后台播放声音内容,并为您的audio会话分配适当的类别。 另请参阅video媒体的特殊注意事项 。