1

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;

}

4

1 に答える 1

1

私のせいですが、上記のコードは正常に動作します。plistファイルの「テスト」コピーに取り組んでいました。ごめん

于 2013-06-14T18:37:12.883 に答える