简体   繁体   中英

Embed AVPlayerViewController In UIView, Loop, and Display Full Screen In Landscape

I have an ultrasound reference application called EchoTools where I loop mp4 videos using the following Swift 5 code within a UIView element on the Storyboard. This app is vertically oriented, but I'd like to display full-screen controls that expand the video and rotate to landscape.

class VideoPlayerLooped {

    public var videoPlayer:AVQueuePlayer?
    public var videoPlayerLayer:AVPlayerLayer?
    var playerLooper: NSObject?
    var queuePlayer: AVQueuePlayer?

    func playVideo(fileName:String, inView:UIView)
    {
        if let path = Bundle.main.path(forResource: fileName, ofType: "mp4")
        {

            let url = URL(fileURLWithPath: path)
            let playerItem = AVPlayerItem(url: url as URL)
            _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
            videoPlayer = AVQueuePlayer(items: [playerItem])
            videoPlayer?.isMuted = true
            videoPlayer?.preventsDisplaySleepDuringVideoPlayback = false
            playerLooper = AVPlayerLooper(player: videoPlayer!, templateItem: playerItem)
            videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
            videoPlayerLayer!.frame = inView.bounds
   
            inView.layer.addSublayer(videoPlayerLayer!)

            videoPlayer?.play()
        }
    }

    func remove()
    {
        videoPlayerLayer?.removeFromSuperlayer()
    }
}

My understanding is that AVPlayerViewController might be necessary, but is it possible to modify the existing code such that I can display the video as it is by default (portrait orientation, looped) while still including the controls inherent to AVPlayerViewController?

Any light that someone can shed will be most appreciated. I've tried searching for solutions and modifying the code with minimal success thus far.

create a method to rotate your video in landscape mode in your VideoPlayerLooped class:

func degreeToRotate(_ x: CGFloat) -> CGFloat {
    return .pi * x / 180.0
}

and add this below lines of code in playVideo(fileName:String, inView:UIView) method to call degreeToRotate() method and to rotate the video in landscape mode:

let affineTransform = CGAffineTransform(rotationAngle: degreeToRotate(90))\
videoPlayerLayer?.setAffineTransform(affineTransform)

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