πŸ“½ A video player for SwiftUI, support for caching, preload and custom control view.

Overview

VideoPlayer

codebeat badge


Demo

Screenshot

  1. Clone or download the project.
  2. In the terminal, run swift package resolve.
  3. Open VideoPlayer.xcodeproj and run Demo target.

Features

  • Fully customizable UI.
  • Plays local media or streams remote media over HTTP.
  • Built-in caching mechanism to support playback while downloading.
  • Can preload multiple videos at any time.
  • Support seek to duration.
  • Simple API.

Quick Start

struct ContentView : View {
    @State private var play: Bool = true
    
    var body: some View {
        VideoPlayer(url: someVideoURL, play: $play)
    }
}

Advances

struct ContentView : View {  
    @State private var autoReplay: Bool = true 
    @State private var mute: Bool = false      
    @State private var play: Bool = true       
    @State private var time: CMTime = .zero  
    
    var body: some View {
        VideoPlayer(url: someVideoURL, play: $play, time: $time)
            .autoReplay(autoReplay)
            .mute(mute)
            .onBufferChanged { progress in
                // Network loading buffer progress changed
            }
            .onPlayToEndTime { 
                // Play to the end time.
            }
            .onReplay { 
                // Replay after playing to the end. 
            }
            .onStateChanged { state in 
                switch state {
                case .loading:
                    // Loading...
                case .playing(let totalDuration):
                    // Playing...
                case .paused(let playProgress, let bufferProgress):
                    // Paused...
                case .error(let error):
                    // Error...
                }
            }
    }
}

Preload

Set the video urls to be preload queue. Preloading will automatically cache a short segment of the beginning of the video and decide whether to start or pause the preload based on the buffering of the currently playing video.

VideoPlayer.preload(urls: [URL])

Set the preload size, the default value is 1024 * 1024, unit is byte.

VideoPlayer.preloadByteCount = 1024 * 1024 // = 1M

Cache

Get the total size of the video cache.

let size = VideoPlayer.calculateCachedSize()

Clean up all caches.

VideoPlayer.cleanAllCache()

Installation

Swift Package Manager

  1. Select Xcode -> File -> Swift Packages -> Add Package Dependency...
  2. Enter https://github.com/wxxsw/VideoPlayer.
  3. Click Next, then select the version, complete.

Requirements

  • iOS 13+
  • Xcode 11+
  • Swift 5+

Thanks

Banner Design by @aduqin

License

VideoPlayer is released under the MIT license. See LICENSE for details.

Comments
  • crash when load next video

    crash when load next video

    Crash will not present if stop video playing before switching next video. But I want auto play when swipe to new video, just like tiktok.

    crash log: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of AVPlayer cannot remove a time observer that was added by a different instance of AVPlayer.'

    source code: `struct ContentView: View { @State private var index = 0 @State private var play: Bool = true var manager: Manager { return Manager.shared } var count: Int { return manager.datas.count } var data: MyData { return manager.datas[index] } var url: URL? { return URL(string: data.url) }

    var body: some View {
        ZStack {
            Rectangle().fill().foregroundColor(.black)
            url.map { VideoPlayer(url: $0, play: $play) }
        }
        .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)
                    .onEnded({ value in
                        if value.translation.height < 0, index < count - 1 {
                            index += 1
                        }
                        if value.translation.height > 0, index > 0 {
                            index -= 1
                        }
                    }))
        .ignoresSafeArea()
    }
    

    }`

    opened by foolbear 7
  • Header Range issue

    Header Range issue

    Sometimes server returns error 416. I suppose this happens because of wrong range header if preload byte count more then file size. Header when error occurs is Range = "bytes=170636-2097151". First index is more then file size too. When header is "bytes=0-2097151" server returns 0 - 170635 with 206 code after that framework make request with out of bounds range "bytes=170636-2097151" but I think it should be "bytes=170635-170636"

    Preconditions: server Amazon CDN, file size = 170636, preloadByteCount = 2097152

    opened by IvanShah 5
  • Add http headers while accessing the video resources?

    Add http headers while accessing the video resources?

    A nice project, but I was wondering how can I add a http header while requesting the video, since I have to check the "token" while the user is trying to fetch that resources. Thanks a lot!

    enhancement 
    opened by czf0613 3
  • This Media Format is Not Supported (.mov file)

    This Media Format is Not Supported (.mov file)

    @wxxsw Hi there - I'm getting this error: Error Error Domain=AVFoundationErrorDomain Code=-11828 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x281bd39c0 {Error Domain=NSOSStatusErrorDomain Code=-12847 "(null)"}}

    trying to play a file like this: https://f000.backblazeb2.com/file/lighthouseStories/641FoyZcKFbHiD1Ceks4-snippet

    This file URL works just fine with the standard AVPlayer, not sure why I'm getting this error. Please advise.

    opened by realjpro 3
  • Error when app is closed

    Error when app is closed

    *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of AVPlayer cannot remove a time observer that was added by a different instance of AVPlayer.'

    opened by ebby 3
  • GSPlayer compilation error on Version 12.0 (12A7208)

    GSPlayer compilation error on Version 12.0 (12A7208)

    Cant run VideoPlayer with iOS 14 using Version 12.0 (12A7208) Method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter 1 cannot be represented in Objective-C on

        @discardableResult
        open func addBoundaryTimeObserver(forTimes times: [CMTime], queue: DispatchQueue? = nil, using: @escaping () -> Void) -> Any? {
            return player?.addBoundaryTimeObserver(forTimes: times.map { NSValue(time: $0) }, queue: queue, using: using)
        }
    

    method in VideoPlayerView.swift

    opened by daihovey 2
  • Multiple Video In a List is Causing an Issue

    Multiple Video In a List is Causing an Issue

    I am using VideoPlayer in List, but the issue I am facing is that first One or Two videos playing correctly, but after I scrolling List View the remaining video did not play properly. Please Help me for that. Thanks in Advance.

    opened by JolChrSA 2
  • Preloading video preview issue

    Preloading video preview issue

    Hello, I'm trying to preload the preview of video using VideoPlayer.preload(), it's not working with me. the preview doesn't show

    @State var url: URL = URL(string: "https://firebasestorage.googleapis.com/v0/b/mozare3-608bc.appspot.com/o/Jellyfish_0.mp4?alt=media&token=9c808983-db70-4128-bf3e-6d087cc6c601")!

    VideoPlayer.preload(urls: [self.url])

    Can you please assist me on how to show the preview ?

    Thanks, Hasan

    opened by hasanals 2
  • Cocoa is not available when building for iOS.

    Cocoa is not available when building for iOS.

    Cocoa is not available when building for iOS. Consider using #if !os(iOS) to conditionally import this framework.

    when I want to build my app I got this error in GSAVPlayerViewController class.

    it was ok on 1.1.6 but after updating to the latest version got this error. my Xcode version: 12.2

    opened by MarsXan 1
  • Quick start not playing

    Quick start not playing

    *Used swift package to create dependency

    *included the following: import AVFoundation import SwiftUI import VideoPlayer import UIKit

    added to plist: App Transport Security Settings -- Allow Arbitrary Loads -- Allow Arbitrary Loads for Media -- AllowArbitrary Loads for Web Content

    However, it is still not playing. Please help

    opened by jclaude33 1
  • Need a seekTo duration method

    Need a seekTo duration method

    In need of a seekTo(duration) method so that we can externally control the progress of a video by integrating it with other elements of our own in the project Much appreciated ! πŸ’―

    opened by TilakMaddy 1
  • Buffering and sound problem

    Buffering and sound problem

    hello, videos from url dont play the sound. Also on slow internet connections, the player buffers alot, how can i set the player to only play when a certain amount of data is predownloaded and pause if the current data is insufficient (specify buffer size)

    opened by coucoseth 3
  • Not effective index changing

    Not effective index changing

    I realized that when we press the next Video button, previous video still tries to complete the download. This situation puts great burden on network load as well as causing dramatic decrease in video download speed. Is there any quick fixes that you can suggest. Otherwise I can work on creating PR. Thank you in advance

    opened by HasanBingolbali 9
  • Cannot allocate memory crash

    Cannot allocate memory crash

    Hello, we are facing several issues in our Crashlytics, it looks like an issue with preloading the cache when there is not enough memory on the device, we support only devices with iOS 14+, full log:

    Fatal Exception: NSFileHandleOperationException 0 CoreFoundation 0x19803186c __exceptionPreprocess 1 libobjc.A.dylib 0x1ad04ac50 objc_exception_throw 2 Foundation 0x1993227f4 -[NSConcreteFileHandle readDataUpToLength:error:] 3 Foundation 0x1992b791c +[NSPropertyListSerialization writePropertyList:toStream:format:options:error:] 4 0x10469e874 VideoDownloaderHandler.processActions() 5 0x10469c388 VideoDownloader.download(from:length:) 6 0x1046a5f70 VideoPreloadManager.start() 7 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 8 0x10469e824 VideoDownloaderHandler.processActions() 9 0x10469e914 VideoDownloaderHandler.processActions() 10 0x10469e914 VideoDownloaderHandler.processActions() 11 0x10469c388 VideoDownloader.download(from:length:) 12 0x1046a5f70 VideoPreloadManager.start() 13 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 14 0x10469e824 VideoDownloaderHandler.processActions() 15 0x10469e914 VideoDownloaderHandler.processActions() 16 0x10469e914 VideoDownloaderHandler.processActions() 17 0x10469c388 VideoDownloader.download(from:length:) 18 0x1046a5f70 VideoPreloadManager.start() 19 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 20 0x10469e824 VideoDownloaderHandler.processActions() 21 0x10469e914 VideoDownloaderHandler.processActions() 22 0x10469e914 VideoDownloaderHandler.processActions() 23 0x10469c388 VideoDownloader.download(from:length:) 24 0x1046a5f70 VideoPreloadManager.start() 25 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 26 0x10469e824 VideoDownloaderHandler.processActions() 27 0x10469e914 VideoDownloaderHandler.processActions() 28 0x10469e914 VideoDownloaderHandler.processActions() 29 0x10469c388 VideoDownloader.download(from:length:) 30 0x1046a5f70 VideoPreloadManager.start() 31 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 32 0x10469e824 VideoDownloaderHandler.processActions() 33 0x10469e914 VideoDownloaderHandler.processActions() 34 0x10469e914 VideoDownloaderHandler.processActions() 35 0x10469c388 VideoDownloader.download(from:length:) 36 0x1046a5f70 VideoPreloadManager.start() 37 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 38 0x10469e824 VideoDownloaderHandler.processActions() 39 0x10469e914 VideoDownloaderHandler.processActions() 40 0x10469e914 VideoDownloaderHandler.processActions() 41 0x10469c388 VideoDownloader.download(from:length:) 42 0x1046a5f70 VideoPreloadManager.start() 43 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 44 0x10469e824 VideoDownloaderHandler.processActions() 45 0x10469e914 VideoDownloaderHandler.processActions() 46 0x10469e914 VideoDownloaderHandler.processActions() 47 0x10469c388 VideoDownloader.download(from:length:) 48 0x1046a5f70 VideoPreloadManager.start() 49 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 50 0x10469e824 VideoDownloaderHandler.processActions() 51 0x10469e914 VideoDownloaderHandler.processActions() 52 0x10469e914 VideoDownloaderHandler.processActions() 53 0x10469c388 VideoDownloader.download(from:length:) 54 0x1046a5f70 VideoPreloadManager.start() 55 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 56 0x10469e824 VideoDownloaderHandler.processActions() 57 0x10469e914 VideoDownloaderHandler.processActions() 58 0x10469e914 VideoDownloaderHandler.processActions() 59 0x10469c388 VideoDownloader.download(from:length:) 60 0x1046a5f70 VideoPreloadManager.start() 61 0x1046a6d98 specialized VideoPreloadManager.downloader(:didFinished:) 62 0x10469e824 VideoDownloaderHandler.processActions() 63 0x10469e914 VideoDownloaderHandler.processActions() 64 0x10469e914 VideoDownloaderHandler.processActions() 65 0x10469c388 VideoDownloader.download(from:length:) 66 F 0x1046a5f70 VideoPreloadManager.start() 67 0x1046a6d98 specialized VideoPreloadManager.downloader(_:didFinished:) 68 0x10469e824 VideoDownloaderHandler.processActions() 69 0x10469e914 VideoDownloaderHandler.processActions() 70 0x10469e914 VideoDownloaderHandler.processActions() 71 0x10469c388 VideoDownloader.download(from:length:) 72 0x1046a5f70 VideoPreloadManager.start() 73 0x1046a5c1c VideoPreloadManager.set(waiting:) 74 0x104691d94 static VideoPlayer.preload(urls:)

    opened by IvanShah 1
Owner
Gesen
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
Gesen
Support customization of any player SDK and control layer

Support customization of any player SDK and control layer

紫枫 6.8k Sep 19, 2022
BMPlayer - A video player for iOS, based on AVPlayer, support the horizontal, vertical screen

A video player for iOS, based on AVPlayer, support the horizontal, vertical screen. support adjust volume, brightness and seek by slide, support subtitles.

Eliyar Eziz 1.8k Sep 17, 2022
Overlay alpha channel video animation player view using Metal.

Overlay alpha channel video animation player view using Metal. Example To run the example project, clone the repo, and run pod install from the Exampl

noppefoxwolf 240 Sep 21, 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 Sep 2, 2022
MMPlayerView - Custom AVPlayerLayer on view and transition player with good effect like youtube and facebook

MMPlayerView Demo-Swift List / Shrink / Transition / Landscape MMPlayerLayer ex. use when change player view frequently like tableView / collectionVie

Millman Yang 723 Sep 5, 2022
Yattee: video player for Invidious and Piped built for iOS 15, tvOS 15 and macOS Monterey

Video player with support for Invidious and Piped instances built for iOS 15, tvOS 15 and macOS Monterey.

Yattee 702 Sep 20, 2022
Yattee: video player for Invidious and Piped built for iOS, tvOS and macOS

Video player for Invidious and Piped instances built for iOS, tvOS and macOS. Features Native user interface built with SwiftUI Multiple instances and

Yattee 709 Sep 21, 2022
Video view controller with Periscope fast rewind control

Periscope-VideoViewController Video view controller with Periscope fast rewind control. Tutorial on how to create this component can be found here. Re

Danil Gontovnik 503 Jul 1, 2022
▢️ video player in Swift, simple way to play and stream media on iOS/tvOS

Player Player is a simple iOS video player library written in Swift. Looking for an obj-c video player? Check out PBJVideoPlayer (obj-c). Looking for

patrick piemonte 2k Sep 21, 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 Sep 21, 2022
YoutubeKit is a video player that fully supports Youtube IFrame API and YoutubeDataAPI for easily create a Youtube app

YoutubeKit YoutubeKit is a video player that fully supports Youtube IFrame API and YoutubeDataAPI to easily create Youtube applications. Important Ref

Ryo Ishikawa 542 Sep 19, 2022
Versatile Video Player implementation for iOS, macOS, and tvOS

News ?? - Since 2.1.3 VersaPlayer now supports iOS, macOS, and tvOS Example Installation Usage Basic Usage Adding Controls Advanced Usage Encrypted Co

Jose Quintero 707 Sep 17, 2022
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
Swifty360Player - iOS 360-degree video player streaming from an AVPlayer.

Swifty360Player iOS 360-degree video player streaming from an AVPlayer. Demo Requirements Swifty360Player Version Minimum iOS Target Swift Version 0.2

Abdullah Selek 142 Sep 2, 2022
VGPlayer - πŸ“Ί A simple iOS video player by Vein.

Swift developed based on AVPlayer iOS player,support horizontal gestures Fast forward, pause, vertical gestures Support brightness and volume adjustment, support full screen, adaptive screen rotation direction.

Wen Rong 394 Aug 29, 2022
Open Source iOS 360 Degree Panorama Video Player.

?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? The Metal with Swift 5.0 version is comming ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 360 VR Player A Open Source, Ad-free, Na

Hanton Yang 2k Sep 24, 2022
FWVideoPlayer is video Player for iOS in Swift.

FWVideoPlayer Desc FWVideoPlayer is video Player for iOS in Swift. It can play video and audio. You can use it easy. Example To run the example projec

null 1 Oct 15, 2021
SuperVideoPlayer is video player in Objc.

SuperVideoPlayer Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation S

null 1 Oct 19, 2021
IINA is the modern video player for macOS.

IINA IINA is the modern video player for macOS. Website Β· Releases Β· Telegram Group Features Based on mpv, which provides the best decoding capacity o

Jesse Chan 0 Nov 2, 2021