简单Swift视频播放器的Objective-C等价物不显示视频

cld4siwp  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(113)

我正在创建一个播放mp4视频的简单故事板。这在Swift中可以正常工作,但是当我尝试在Objective-C中做同样的事情时,什么也没发生。有人能看看我在从Swift转换而来的Objective-C代码中做错了什么吗?
注:

  • 除视图控制器实现外,两个项目均为空
  • 视频文件anim2.mp4确实包含在两个项目中
  • 由于技术原因,视频播放器必须使用Objective-C

代码:

// Swift implementation
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    let path = Bundle.main.path(forResource: "anim2", ofType:"mp4");
    let url = NSURL(fileURLWithPath: path!) as URL;
    let player = AVPlayer(url: url);
    let playerLayer = AVPlayerLayer(player: player);
    playerLayer.frame = self.view.bounds;
    self.view.layer.addSublayer(playerLayer);
    player.play();
  }
}

// Objective-C implementation
#import "ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
  [super viewDidLoad];
  NSString* path = [[NSBundle mainBundle] pathForResource:@"anim2" ofType:@"mp4"];
  NSURL* url = [NSURL fileURLWithPath:path isDirectory:false];
  AVPlayer* player = [[AVPlayer alloc] initWithURL:url];
  AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithLayer:player];
  playerLayer.frame = self.view.bounds;
  [self.view.layer addSublayer:playerLayer];
  [player play];
}
@end
h4cxqtbf

h4cxqtbf1#

这一行不一样:

AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithLayer:player];

它试图把AVPlayer当作CALayer,这会悄悄地失败,这里没有警告,因为initWithLayer:id作为它的类型。
你的意思是:

AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer: player];

相关问题