简体   繁体   English

iOS AVPlayerLayer无法播放本地视频

[英]iOS AVPlayerLayer not playing local video

I've been trying to get an AVPlayerLayer to play a video that is downloaded off the internet in my app. 我一直在尝试获取AVPlayerLayer来播放从我的应用程序中从互联网下载的视频。 However, despite all the help online, I can't seem to get it to work. 但是,尽管在线上提供了所有帮助,但我似乎无法使其正常工作。 Here's the code: 这是代码:

import UIKit
import CoreGraphics
import AVFoundation
import XCPlayground
XCPExecutionShouldContinueIndefinitely()

var url = NSURL(string: "/Users/MyUsername/Desktop/Video.mp4")
//var url = NSURL(string: "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/MediaCoder/MediaCoder_test2_1m10s_XVID_VBR_131kbps_480x320_25fps_AACLCv4_VBR_32kbps_Stereo_24000Hz.mp4")
println(url.absoluteString)

var exists = NSFileManager.defaultManager().fileExistsAtPath(url.absoluteString)
println(exists ? "true" : "false")

var playerAsset = AVURLAsset(URL: url, options: nil)
playerAsset.loadValuesAsynchronouslyForKeys(
    ["duration"],
    completionHandler: {
        var error: NSError?
        switch playerAsset.statusOfValueForKey("duration", error: &error) {
        case AVKeyValueStatus.Loaded:
            println("Duration: \(playerAsset.duration)")
        default:
            println("Failed duration")
        }
    })

var playerItem = AVPlayerItem(asset: playerAsset)

var player =  AVPlayer(playerItem: playerItem)

var movieLayer = AVPlayerLayer(player: player)

movieLayer.backgroundColor = UIColor.redColor().CGColor
movieLayer.frame = CGRect(x: 25, y: 25, width: 100, height: 100)
movieLayer.opacity = 1.0

player.play()

var view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
view.layer.addSublayer(movieLayer)

XCPShowView("Movie View", view)

This is the output: 这是输出:

在此处输入图片说明

The file exists (which is proved on line 12), but it doesn't seem to load the video properly (as seen on line 15). 该文件存在(在第12行上证明),但似乎无法正确加载视频(如第15行所示)。

The odd thing is that it works perfectly if you give it a remote URL. 奇怪的是,如果给它一个远程URL,它会完美地工作。 (To see that, comment out the first line and uncomment the second.) (要看到这一点,请注释掉第一行,然后取消注释第二行。)

If someone could help me, that'd be great. 如果有人可以帮助我,那就太好了。

Thanks! 谢谢!

Edit: Sorry, streaming the video doesn't work in a playground, if you're trying to run it. 编辑:很抱歉,如果您要运行视频,则无法在操场上播放视频。 You'll have to put it inside an app and run it in the simulator. 您必须将其放入应用程序中并在模拟器中运行。

Make sure that the file version of the URL has "file://" in front of it. 确保URL的文件版本前面带有“ file://”。 Try the code below: 请尝试以下代码:

var url = NSURL(string: "file://Users/MyUsername/Desktop/Video.mp4")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM