AVPlayer 和背景音频流
Posted
技术标签:
【中文标题】AVPlayer 和背景音频流【英文标题】:AVPlayer & background audio streaming 【发布时间】:2013-06-12 14:52:16 【问题描述】:我无法让 AVPLayer 在后台工作,它在应用程序启动时完美运行,但当我按下主页按钮(在设备中)时,声音停止。 有什么问题?
这是 APPNAME-.plist:
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
我在 AppDelegate.h 中有这段代码:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
然后在 AppDelegate.m 中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSURL *url = [NSURL URLWithString:@"mp3url"];
// You may find a test stream at <http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8>.
self.playerItem = [AVPlayerItem playerItemWithURL:url];
[_playerItem addObserver:self forKeyPath:@"status" options:0 context:&ItemStatusContext];
self.player = [AVPlayer playerWithPlayerItem:_playerItem];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
那么在这个方法中:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
if (context == &ItemStatusContext)
NSLog(@"context?");
AVPlayer *thePlayer = (AVPlayer *)object;
if ([thePlayer status] == AVPlayerStatusFailed)
NSLog(@"error");
// Respond to error: for example, display an alert sheet.
return;
if ([thePlayer status] == AVPlayerStatusReadyToPlay)
NSLog(@"ready");
[[AVAudiosession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
error:nil];
[[AVAudioSession sharedInstance] setActive:YES
error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[_player play];
return;
if ([thePlayer status] == AVPlayerStatusUnknown)
NSLog(@"unknown");
// Deal with other status change if appropriate.
// Deal with other change notifications if appropriate.
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
return;
【问题讨论】:
我已经验证了这段代码,它对我来说工作正常。我已经在 iphone 4s 上测试过了。 @Norbert 感谢您的回答。我的错,我只是在处理 plist 文件的“测试”副本.... 有人有最新的 Swift 解决方案吗? 【参考方案1】:我的错,上面的代码工作正常。我只是在处理 plist 文件的“测试”副本。对不起
【讨论】:
以上是关于AVPlayer 和背景音频流的主要内容,如果未能解决你的问题,请参考以下文章