如何使用Swift播放本地视频? [英] How to play a local video with Swift?

查看:1136
本文介绍了如何使用Swift播放本地视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的 mp4 视频文件,我已添加到我当前的Xcode6 Beta项目中。

I have a short mp4 video file that I've added to my current Xcode6 Beta project.

我想在我的应用中播放视频。

在搜索数小时后,我找不到任何远程帮助。有没有办法用Swift完成这个或你必须使用Objective-C?
我可以指出正确的方向吗?我不能成为唯一想知道这一点的人。

After hours searching, I can't find anything remotely helpful. Is there a way to accomplish this with Swift or do you have to use Objective-C? Can I get pointed in the right direction? I can't be the only one wondering this.

推荐答案

当然可以使用Swift!

Sure you can use Swift!

将视频(我们称之为 video.m4v )添加到您的Xcode项目

Add the video (lets call it video.m4v) to your Xcode project

打开 Project Navigator cmd + 1

然后选择你的项目根目录> 你的目标> 构建阶段> 复制捆绑资源

Then select your project root > your Target > Build Phases > Copy Bundle Resources.

您的视频必须在这里。如果不是,那么你应该使用加号按钮添加它

Your video MUST be here. If it's not, then you should add it using the plus button

打开View Controller并编写此代码。

Open your View Controller and write this code.

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()
    }

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        present(playerController, animated: true) {
            player.play()
        }
    }
}

这篇关于如何使用Swift播放本地视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆