MMPlayerView - Custom AVPlayerLayer on view and transition player with good effect like youtube and facebook

Related tags

Video MMPlayerView
Overview

MMPlayerView

paypal

CI Status Version License Platform

Demo-Swift

List / Shrink / Transition / Landscape

list shrink transition landscape

MMPlayerLayer

ex. use when change player view frequently like tableView / collectionView
import MMPlayerView
mmPlayerLayer.playView = cell.imgView
mmPlayerLayer.getStatusBlock { [weak self] (status) in

}
self.mmPlayerLayer.set(url: DemoSource.shared.demoData[indexPath.row].play_Url)
self.mmPlayerLayer.resume()

Transition

##PresentedViewController
1. Set transition config
    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
        self.mmPlayerTransition.present.pass { (config) in
            // setting
            .....
        }
    }
2. Set MMPLayerToProtocol on PresentedViewController
3. Set MMPlayerPrsentFromProtocol on PresentingViewController

Landscape

1.Set MMPlayerLayer
   // roation screen to landscape can change player to fullscreen
   mmplayerLayer.fullScreenWhenLandscape = true
   
2. Set from code
   mmplayerLayer.setOrientation(.landsacpeLeft)
   
3. Observer
  mmPlayerLayer.getOrientationChange { (status) in
        print("Player OrientationChange \(status)")
  }

Cover View

landscape

## add cover item view on player
play.replace(cover: CoverA.instantiateFromNib())

Progress

// Custom your progress view and it will add on player center
// view need to implement ProgressProtocol, and add progress in this view, when start/stop control what need to do
.custom(view: <#T##MMProgressProtocol#>)
 public protocol MMProgressProtocol {
     func start()
     func stop()
 }

Cache

playerLayer.cacheType = .memory(count: 10)
public enum MMPlayerCacheType {
    case none
    case memory(count: Int) // set this to cache seek time in memory and if cache out of count will remove first you    
    stored
}

Layer Protocol

// detect if touch in videoRect
// if touch out of videoRect will not trigger show/hide cover view event
public protocol MMPlayerLayerProtocol: class {

func touchInVideoRect(contain: 

) // 
}

Downloader

        var downloadObservation: MMPlayerObservation?

        downloadObservation = MMPlayerDownloader.shared.observe(downloadURL: downloadURL) { [weak self] (status) in
            switch status {
            case .cancelled:
                print("Canceld")
            case .completed:
                DispatchQueue.main.async {
                    self?.downloadBtn.setTitle("Delete", for: .normal)
                    self?.downloadBtn.isHidden = false
                    self?.progress.isHidden = true
                }
            case .downloading(let value):
                self?.downloadBtn.isHidden = true
                self?.progress.isHidden = false
                self?.progress.progress = value
                print("Exporting \(value) \(downloadURL)")
            case .failed(let err):
                DispatchQueue.main.async {
                    self?.downloadBtn.setTitle("Download", for: .normal)
                }
                
                self?.downloadBtn.isHidden = false
                self?.progress.isHidden = true
                print("Download Failed \(err)")
            case .none:
                DispatchQueue.main.async {
                    self?.downloadBtn.setTitle("Download", for: .normal)
                }
                self?.downloadBtn.isHidden = false
                self?.progress.isHidden = true
            case .exist:
                DispatchQueue.main.async {
                    self?.downloadBtn.setTitle("Delete", for: .normal)
                }
                self?.downloadBtn.isHidden = false
                self?.progress.isHidden = true
            }

Delete

        if let info = MMPlayerDownloader.shared.localFileFrom(url: downloadURL)  {
            MMPlayerDownloader.shared.deleteVideo(info)
        }

Subtitle

     let subTitleStr = Bundle.main.path(forResource: "test", ofType: "srt")!
         if let str = try? String.init(contentsOfFile: subTitleStr) {
             self.mmPlayerLayer.subtitleSetting.subtitleType = .srt(info: str)
             self.mmPlayerLayer.subtitleSetting.defaultTextColor = .red
             self.mmPlayerLayer.subtitleSetting.defaultFont = UIFont.boldSystemFont(ofSize: 20)
         }
     }

Shrink

    // Return a view which you want back
    self.mmPlayerLayer.shrinkView(onVC: self, isHiddenVC: false) { [weak self] () -> UIView? in
        guard let self = self, let path = self.findCurrentPath() else {return nil}
        let cell = self.findCurrentCell(path: path) as! PlayerCell
        self.mmPlayerLayer.set(url: cell.data!.play_Url)
        self.mmPlayerLayer.resume()
        return cell.imgView
    }
    // Check player is shrink or not
    self.mmPlayerL.isShrink

Demo-SwiftUI

Control

let control = MMPlayerControl()
//Play
control.set(url: self.videoList[idx].play_Url)
control.resume()
//InValidate
control.invalidate()
//Observation parameter
@Published
public var orientation: PlayerOrientation = .protrait
@Published
public var timeInfo = TimeInfo()
@Published
public var isMuted = false
@Published
public var isBackgroundPause = true
@Published
@Published
public var repeatWhenEnd: Bool = false
@Published
public var isLoading: Bool = false
public var cacheType: PlayerCacheType = .none
@Published
public private(set) var isCoverShow = false
@Published
public var autoHideCoverType = CoverAutoHideType.disable
public var coverAnimationInterval = 0.3
@Published
public var error: MMPlayerViewUIError?

Init View

let player = MMPlayerViewUI(control: self.control, cover: CoverAUI())

Download

view.modifier(MMPlayerDownloaderModifier(url: obj.play_Url!, status: $downloadStatus))

Transition Player

//func playerTransition(view: Content, from: CGRect?) -> AnyTransition
if showDetailIdx != nil {
    DetailView(obj: self.playListViewModel.videoList[showDetailIdx!], showDetailIdx: $showDetailIdx)
       .edgesIgnoringSafeArea(.all)
       .transition(.playerTransition(view: MMPlayerViewUI(control: control) ,from: fromFrame))
        .zIndex(1)
}
// Trigger transition
withAnimation { 
      self.fromFrame = obj.frame
      self.showDetailIdx = offset
}

Requirements

iOS 12.0+
Swift 5.0+

Installation

MMPlayerView is available through CocoaPods. To install it, simply add the following line to your Podfile:

Swift 5 
pod 'MMPlayerView'

Author

[email protected]

License

MMPlayerView is available under the MIT license. See the LICENSE file for more info.

Comments
  • Failed to load the video URL

    Failed to load the video URL

    In my case: Am using MMPlayerView in collectionview cell to load multiple videos and play simultaneously.

    issue Getting error like below while load the video in some cases like Enter into the view controller and load the collectionView again and again in certain point the black screen will appear and status comes like below failed(err: "Cannot Decode").

    opened by kavinkraken 0
  • Video stop playing when you are on the call or any other background Audio progress

    Video stop playing when you are on the call or any other background Audio progress

    I am creating a view like TikTok its working everything fine when I pick the call video is stop playing even I have forced to resume or play its fails always

    opened by sumitAndrewMethu 0
  • Video Freezes in iOS 15

    Video Freezes in iOS 15

    Hey, I'm facing issue on iOS 15. When I load video 1st time from URL it worked well, But when we load same video from Cache then it's not working. Only Sound is coming but video getting Freezes.

    Please share the solution.

    Thanks in advance!!

    opened by HB-Krutagn 2
  • Play Multiple Video in Single Cell

    Play Multiple Video in Single Cell

    Hi, I want to play Multiple Video in Single cell like Stores, I have updated the video URL once Pause the first video in same cell URL is updating but play first video.

    Thanks

    opened by techhirasky 0
  • mmplayer block apple music

    mmplayer block apple music

    hi, im write mmplayer in collection view cell as silent preview mode, the problem is when im playing apple music, and open app, mmPlayercell start -> apple music stop. How can i prevent it? Thanks

    opened by fukemy 1
  • exception can remove observer

    exception can remove observer

    i got this error, please help:

    Ảnh chụp Màn hình 2021-04-03 lúc 14 09 09 code:

    @objc fileprivate func startLoading() {
            self.updateByContentOffset()
            if self.presentedViewController != nil {
                return
            }
            print("play : \(mmPlayerLayer.playUrl)")
            // start loading video
            mmPlayerLayer.resume()
        }
        
        fileprivate func updateByContentOffset() {
            if let path = findFirstMediaCellVisible(), self.presentedViewController == nil {
                self.updateCell(at: path)
            }
        }
        
        private func findFirstMediaCellVisible() -> IndexPath? {
            let visible = messagesCollectionView.indexPathsForVisibleItems
            guard visible.count > 0 else { return nil }
            
            return visible.first(where: { messagesCollectionView.cellForItem(at: $0) is MediaMessageCell} )
        }
        
        func updateCell(at indexPath: IndexPath) {
            print("updateCell: \(NSStringFromClass(messagesCollectionView.cellForItem(at: indexPath)!.classForCoder))")
            let message = messageList[indexPath.section]
            guard case let .video(videoItem) = message.kind else { return }
            if let cell = messagesCollectionView.cellForItem(at: indexPath) as? MediaMessageCell {
                // this thumb use when transition start and your video dosent start
    //            mmPlayerLayer.thumbImageView.image = cell.im
                // set video where to play
                print("set mm for index: \(indexPath) - \(message.sender.displayName)")
                mmPlayerLayer.playView = cell.imageView
                mmPlayerLayer.set(url: videoItem.url)
            }
        }
    
    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            
            
            offsetObservation = messagesCollectionView.observe(\.contentOffset, options: [.new]) { [weak self] (_, value) in
                guard let self = self, self.presentedViewController == nil else {return}
                NSObject.cancelPreviousPerformRequests(withTarget: self)
                self.perform(#selector(self.startLoading), with: nil, afterDelay: 0.2)
            }
        }
        
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            NotificationCenter.default.removeObserver(self)
            mmPlayerLayer.player?.pause()
        }
    
    opened by fukemy 1
Owner
Millman Yang
Millman Yang
Youtube-like double tap to forward/rewind animation with ripple effect.

VideoQuickSeeking Youtube-like double tap to forward/rewind animation with ripple effect. Please feel free to make pull requests. Example To run the e

Hai Pham 3 Dec 7, 2022
VIMVideoPlayer is a simple wrapper around the AVPlayer and AVPlayerLayer classes.

VIMVideoPlayer is a simple wrapper around the AVPlayer and AVPlayerLayer classes.

Vimeo 280 May 11, 2022
YouTube video player for iOS, tvOS and macOS

About XCDYouTubeKit is a YouTube video player for iOS, tvOS and macOS. Are you enjoying XCDYouTubeKit? You can say thank you with a tweet. I am also a

Cédric Luthi 2.9k Jan 7, 2023
WatchTube: a standalone WatchOS youtube player utilizing Download API for search data and video streaming

WatchTube is a standalone WatchOS youtube player utilizing Download API for sear

WatchTubeTeam 11 May 30, 2022
YouTube player for SwiftUI

SwiftUI YouTube Player for iOS and MacOS Fully functional, SwiftUI-ready YouTube player for iOS 14+ and MacOS 11+. Actions and state are both delivere

Gordan Glavaš 12 Dec 25, 2022
An alternative to SwiftUI's VideoPlayer that includes an overlay button that will transition the player to be presented full screen.

The VideoPlayer provided by SwiftUI out of the box is great but it's missing one very important feature: full screen presentation mode. AZVideoPlayer behaves pretty much exactly like VideoPlayer, but adds the button that's provided by AVPlayerViewController to go full screen.

Adam Zarn 6 Dec 25, 2022
Musical Player - A Simple Musical Player For iOS

Musical_Player The app is a musical player. It was written as an task for a mobi

null 1 Nov 26, 2022
Loop videos on iOS and Android (assuming only one video like on YouTube)

Mobile Video Loop By: Andrew-Chen-Wang iOS Safari Extension (soon Android) that lets you loop a video on your current website. This only works for the

Andrew Chen Wang 0 Dec 19, 2021
📽 A video player for SwiftUI, support for caching, preload and custom control view.

Features QuickStart Advances Installation Requirements License Demo Clone or download the project. In the terminal, run swift package resolve. Open Vi

Gesen 437 Jan 5, 2023
Player View is a delegated view using AVPlayer of Swift

PlayerView [![CI Status](http://img.shields.io/travis/David Alejandro/PlayerView.svg?style=flat)](https://travis-ci.org/David Alejandro/PlayerView) An

null 131 Oct 25, 2022
Swift library for embedding and controlling YouTube videos in your iOS applications via WKWebView!

YouTubePlayer Embed and control YouTube videos in your iOS applications! Neato, right? Let's see how it works. 0.7.0 Update: WKWebView breaking change

Giles Van Gruisen 825 Jan 3, 2023
This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable coding methodologies!

YouTubeClone This project is a clone of YouTube. But the main intention is to show how to write clean code, using proper MVC patterns and re-usable co

Vamshi Krishna 169 Dec 10, 2022
YouTubePlayerKit A Swift Package to easily play YouTube videos 📺

A Swift Package to easily play YouTube videos ??

Sven Tiigi 304 Jan 7, 2023
Lightweight YouTube Downloader for iOS

DownTube DownTube is a very lightweight app that allows you to download any YouTube video for offline use. Note: this app goes against YouTube's TOS a

Adam Boyd 158 Dec 10, 2022
The front-end of youtube iOS app developed using swift 5

Youtube-Front-end-iOS The front-end of youtube iOS app developed using swift 5 UIs 1)-The UI that corresponds to Home Tab bar "The first View " The fi

null 1 Nov 28, 2021
📺 A news app using YouTube playlists, built with React Native

NewsWatch-React-Native A YouTube News app for iOS, made with React-Native. Enjoy watching your daily news. Screencast: This project was bootstrapped w

brad oyler 156 Jun 8, 2022
MacTube is a webview wrapper for YouTube for Mac OS.

MacTube MacTube is a webview wrapper for YouTube for Mac OS. It was made for peo

null 33 Dec 26, 2022
A YouTube copy for the Victor Roldan Dev channel

YouTubeClone La idea de la creación de este proyecto, es que tu tengas la oportunidad de ver como es el desarrollo completo de una aplicación, desede

Victor Roldan 11 Dec 27, 2022
Hide the "Latest Video Performance" tab in YouTube Studio

Hide Latest Video Performance - YT Studio Extension that hides the stupid YouTube Studio "Latest Video Performance" / "Latest YouTube Short Performanc

Taranasus 2 Jul 22, 2022