提问人:Viktor Sehr 提问时间:2/18/2023 更新时间:2/19/2023 访问量:25
Objective-C 等同于简单的 Swift 视频播放器不显示视频
Objective-C equivalent of simple Swift video player does not show video
问:
我正在创建一个简单的故事板来播放 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
答:
1赞
Rob Napier
2/19/2023
#1
这一行是不一样的:
AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithLayer:player];
它试图将 AVPlayer 视为 CALayer,这将悄悄地失败。您不会在此处收到警告,因为 takes 作为其类型。initWithLayer:
id
你的意思是:
AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer: player];
评论