简体   繁体   English

AVPlayer和背景音频流

[英]AVPlayer & background audio streaming

I cannot make AVPLayer work in background, it works perfect when the app starts but when i push the home button (in the device) the sound stops. 我无法使AVPLayer在后台运行,当应用启动时,它可以完美工作,但是当我按“主页”按钮(在设备中)时,声音停止。 What is the problem? 问题是什么?

this is the APPNAME-.plist: 这是APPNAME-.plist:

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

i have this code in AppDelegate.h: 我在AppDelegate.h中有以下代码:

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

then in AppDelegate.m 然后在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;}

then in this method: 然后用这种方法:

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

} }

My fault, the code above works fine. 我的错,上面的代码工作正常。 I was just working on a "test" copy of the plist file. 我只是在处理plist文件的“测试”副本。 Sorry 抱歉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM