2013-06-12 61 views
1

我不能使AVPLayer在後臺工作,它的工作原理完美時,應用程序啓動,但當我按主頁按鈕(在設備)聲音停止。 問題是什麼?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; 

}

+1

我已驗證此代碼,其工作正常。我已經在iphone 4s上測試過它。 – iCoder

+0

@Norbert謝謝你的回答。我的錯,我只是在製作plist文件的「測試」副本。 –

+0

有人有最新的Swift解決方案嗎? – Kaptain

回答

1

我的錯,上面的代碼工作正常。我只是在製作plist文件的「測試」副本。對不起