2017-02-23 179 views
0

蘋果斯威夫特版本3.0.2(swiftlang-800.0.63鐺 - 800.0.42.1)如何使用AVPlayer播放視頻?

我想使用AVPlayer從互聯網上播放視頻。 但是,在源列表下面的AVPlayer.swift中發生「super.init(frame:frame)」錯誤。

主題1:EXC_BAD_ACCESS(代碼= 2,地址= 0x16fc07fe0) enter image description here

如何播放使用AVPlayer視頻? 如果除了錯誤點以外有錯誤的地方,請讓我知道。

AVPlayerView.swift

import Foundation 
import UIKit 

final class AVPlayerView : UIView { 
    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder)! 
    } 
    override init(frame: CGRect) { 
     super.init(frame: frame) 
    } 
    override public class var layerClass: Swift.AnyClass { 
     get { 
      return AVPlayerView.self 
     } 
    } 

}

ViewController.swift

import UIKit 
import AVFoundation 
import CoreMedia 

class ViewController: UIViewController { 
    var playerItem : AVPlayerItem! 
    var videoPlayer : AVPlayer! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let url:NSURL = NSURL(string: "https://aaa.com/test.m3u8")! 
     let avAsset = AVURLAsset(url: url as URL, options: nil) 

     playerItem = AVPlayerItem(asset: avAsset) 

     videoPlayer = AVPlayer(playerItem: playerItem) 

     print(self.view.bounds) 
     let videoPlayerView = AVPlayerView(frame: self.view.bounds) 

     let layer = videoPlayerView.layer as! AVPlayerLayer 
     layer.videoGravity = AVLayerVideoGravityResizeAspect 
     layer.player = videoPlayer 

     self.view.layer.addSublayer(layer) 
     videoPlayer.play() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

回答

1

這裏是代碼播放視頻:

let videoURL = NSURL(string: "PUT_YOUR_PROPER_URL") 
let playerAV = AVPlayer(url: videoURL! as URL) 
let playerLayerAV = AVPlayerLayer(player: playerAV) 
playerLayerAV.frame = self.view.bounds 
self.view.layer.addSublayer(playerLayerAV) 
playerAV.play() 

AVPlayer支持以下擴展名:

public.mpeg 
public.mpeg-2-video 
public.avi 
public.aifc-audio 
public.aac-audio 
public.mpeg-4 
public.au-audio 
public.aiff-audio 
public.mp2 
public.3gpp2 
public.ac3-audio 
public.mp3 
public.mpeg-2-transport-stream 
public.3gpp 
public.mpeg-4-audio 

確保您可以在AVPlayer使用支持的視頻。

+0

AVPlayer是否支持httpu實時流式傳輸m3u8? HLS包含H.264和aac的ts文件。 – Ubunkun

+0

我只是檢查你的網址,但它不工作。 – Nirmalsinh

+0

是的,網址已更改。 iPhone的瀏覽器可以播放網址。 – Ubunkun