简体   繁体   中英

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. 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).

The odd thing is that it works perfectly if you give it a remote 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. Try the code below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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