IOS AVPlayer不会播放视频

时间:2013-05-12 15:50:19

标签: ios video ios6 avplayer

我正在尝试播放视频,因为我从教程中获得了一些代码,但它不起作用。

这是我使用的代码:

- (void) viewDidAppear:(BOOL)animated
{
    avAsset = [AVAsset assetWithURL:[NSURL URLWithString:filePath]];
    avPlayerItem =[avPlayerItem initWithAsset:avAsset];
    avPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
    avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
    [avPlayerLayer setFrame:self.view.frame];
    [self.view.layer addSublayer:avPlayerLayer];
    [avPlayer seekToTime:kCMTimeZero];
    [avPlayer play];

}

我不知道它有什么不对,它没有给出任何错误它只是给了黑屏。 感谢。

4 个答案:

答案 0 :(得分:36)

嘿伙计们感谢s1mon和matt的帮助

以下是可能对某人有所帮助的新代码:

- (void) viewDidAppear:(BOOL)animated
{
    avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:filePath]];
    avPlayerItem =[[AVPlayerItem alloc]initWithAsset:avAsset];
    avPlayer = [[AVPlayer alloc]initWithPlayerItem:avPlayerItem];
    avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:avPlayer];
    [avPlayerLayer setFrame:self.view.frame];
    [self.view.layer addSublayer:avPlayerLayer];
    //[avPlayerLayer setBackgroundColor:[[UIColor redColor]CGColor]];
    [avPlayer seekToTime:kCMTimeZero];
    [avPlayer play];

}

THXXXXXXXX家伙:D

答案 1 :(得分:12)

这可能不是实际问题,但这段代码肯定是错误的:

[NSURL URLWithString:filePath]

首先,尽量不要以文件路径开头;从文件URL开始。这样,就不需要转换。但是,如果必须执行从文件路径到URL的转换,请使用fileURLWithPath:isDirectory:。文件URL是一种特殊的动物,当你从路径转换时,你必须特别要求它。

答案 2 :(得分:3)

我认为您忘记在此行中创建AVPlayerItem的实例:

avPlayerItem =[avPlayerItem initWithAsset:avAsset];

这只会将initWithAsset:发送到avPlayerItem(调用此方法时可能为nil)。尝试更改它以实例化一个新的AVPlayerItem,然后您可以将其分配给avPlayerItem,如下所示:

avPlayerItem = [[AVPlayerItem alloc] initWithAsset:avAsset];

答案 3 :(得分:1)

对于那些寻找swift 2.0 version的人来说,这对我有用。欢呼声。

import Foundation
import UIKit
import AVKit

class VideoViewController: AVPlayerViewController {

    override func viewDidAppear(animated: Bool) {
        self.setupVideoPlayerView()
    }
    private func setupVideoPlayerView()
    {
        let path = "HTTP_VIDEO_URL_HERE"
        let nsURL = NSURL(string: path)
        let avAsset = AVAsset(URL: nsURL!)
        let avPlayerItem = AVPlayerItem(asset: avAsset)

        let avPlayer = AVPlayer(playerItem: avPlayerItem)
        let avPlayerLayer = AVPlayerLayer(layer: avPlayer)

        avPlayerLayer.frame = self.view.frame
        self.view.layer.addSublayer(avPlayerLayer)

        self.player = avPlayer

        self.player!.seekToTime(kCMTimeZero)
        self.player!.play()

    }

}