You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift简单视频播放器转Objective-C后无法播放问题排查

问题:Swift视频播放代码转Objective-C后无响应

我正在开发一个播放mp4视频的简单故事板,Swift版本能正常运行,但转换为Objective-C版本后完全没有反应。

说明

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

代码对比

Swift 实现(可正常运行)

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 实现(无响应版本)

#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

解决方案

问题核心在于AVPlayerLayer的初始化方式错误:Objective-C代码中误用了initWithLayer:方法,这个方法是CALayer的通用初始化方法,用于复制已有图层,无法关联AVPlayer。

正确的做法是使用AVPlayerLayer专属的初始化方法,将播放器与图层绑定。

修正后的Objective-C代码

#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"];
  if (!path) {
      NSLog(@"视频文件未找到");
      return;
  }
  
  NSURL* url = [NSURL fileURLWithPath:path isDirectory:NO];
  AVPlayer* player = [[AVPlayer alloc] initWithURL:url];
  
  // 修正:使用正确的初始化方法关联AVPlayer
  AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
  // 也可以用实例方法:AVPlayerLayer* playerLayer = [[AVPlayerLayer alloc] initWithPlayer:player];
  
  // 设置视频适配模式(可选优化)
  playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
  playerLayer.frame = self.view.bounds;
  
  [self.view.layer addSublayer:playerLayer];
  [player play];
}
@end

关键修正点

  1. 将[[AVPlayerLayer alloc] initWithLayer:player]替换为[AVPlayerLayer playerLayerWithPlayer:player]或[[AVPlayerLayer alloc] initWithPlayer:player],确保图层与播放器绑定
  2. 增加视频文件存在性判断,提升代码健壮性
  3. 可选添加videoGravity属性,让视频按比例适配视图

内容的提问来源于stack exchange,提问作者Viktor Sehr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 08:59:21