【发布时间】:2019-09-27 18:44:40
【问题描述】:
根据 Apple 的文档,当您想在后台播放视频的音频内容时,您必须在将应用程序移至后台时断开 AVPlayer 与其 AVPlayerViewController 或 AVPlayerLayer 的连接,以防止自动暂停的音频:
我注意到在 iOS 13 中,这样做会导致隐藏式字幕中断。我创建了一个新项目(单视图应用程序)来为这个问题创建一个最小的复制案例。我的故事板由一个带有单个按钮的视图组成,并且该按钮作为一个动作(“playPressed”)连接到我的视图控制器。这是我ViewController.m的代码:
//
// ViewController.m
// AVPlayerViewControllerBug
//
// Created by Steven Barnett on 9/27/19.
// Copyright © 2019 BlueFrame Tech. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
{
@private
AVPlayerViewController *controller;
AVPlayer *player;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
controller = [[AVPlayerViewController alloc] init];
player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:@"https://vcloud.blueframetech.com/file/hls/143758.m3u8"]];
controller.player = player;
[player addObserver:self forKeyPath:@"rate" options:0 context:nil];
}
- (IBAction)playPressed:(id)sender {
[self presentViewController:controller animated:YES completion:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// Since we're ONLY observing "rate" on the player, assume
// that's what changed to call this
AVPlayer *player = (AVPlayer*)object;
if (player.rate == 0)
{
// Unbind the player from the view controller when paused
controller.player = nil;
// Since I haven't built custom controls for the player,
// when it's unbound there's no way to hit the play
// button. So we'll just start playing after a timer
// has elapsed
[NSTimer scheduledTimerWithTimeInterval:2.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
[player play];
}];
}
else
{
// Re-bind the player when playing
controller.player = player;
}
}
@end
如果您将此代码复制到您自己的应用程序中,或者自己尝试一下,您会发现当调用controller.player = nil 时,它会导致字幕在AVPlayer 上停止工作。我发现修复它的唯一方法是删除 AVPlayer 对象并创建一个全新的 AVPlayer 来替换它。
有什么我遗漏的东西,一些我不知道的方法调用,还是我误解了什么?还是这只是 iOS 13 的一个错误?
【问题讨论】:
标签: ios objective-c avplayer