簡體   English   中英

AVPlayer和背景音頻流

[英]AVPlayer & background audio streaming

我無法使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;

}

我的錯,上面的代碼工作正常。 我只是在處理plist文件的“測試”副本。 抱歉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM