6

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

这是我使用的代码:

- (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

4 回答 4

36

感谢 s1mon 和马特的帮助。

这是可能对某人有帮助的新代码:

- (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];

}

谢谢你。

于 2013-05-12T17:40:15.307 回答
12

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

[NSURL URLWithString:filePath]

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

于 2013-05-12T16:26:12.270 回答
3

我想你忘了AVPlayerItem在这一行创建一个实例:

avPlayerItem =[avPlayerItem initWithAsset:avAsset];

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

avPlayerItem = [[AVPlayerItem alloc] initWithAsset:avAsset];
于 2013-05-12T16:20:50.253 回答
2

对于那些寻找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()

    }

}
于 2016-08-23T13:30:45.407 回答