πŸ“½ 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
  • AVFoundation issues - Can't play URLs from firebase

    AVFoundation issues - Can't play URLs from firebase

    Hi! I am having an issue trying to play a video that I get from Firebase.

    Error: Error Domain=AVFoundationErrorDomain Code=-11828 "Cannot Open" UserInfo={NSLocalizedFailureReason=This media format is not supported., NSLocalizedDescription=Cannot Open, NSUnderlyingError=0x600003f987b0 {Error Domain=NSOSStatusErrorDomain Code=-12847 "(null)"}}

    According to apple, Code= -11828 is The system can’t open the file because it’s in an unrecognized format. I couldn't find what Code=-12847 is.

    These video urls don't come with the extension of the file, like .mov or .mp4. I tried to apply it manually without success. They work on browser and they work when I try to use AVPlayer.

    Any idea of what might be going wrong? I really want to use this library as it's very complete and well done :)

    I'm sorry I can't give you any links, but I can give you any other information that could help. Thanks!

    opened by juliaYamamoto 2
  • 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
Owner
Gesen
β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”
Gesen
Support customization of any player SDK and control layer

Support customization of any player SDK and control layer

紫枫 6.9k Dec 30, 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 Jan 4, 2023
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 244 Jan 1, 2023
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
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 724 Nov 24, 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 504 Dec 20, 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 1k Dec 27, 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 1.1k Jan 8, 2023
▢️ 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 Jan 2, 2023
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
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 555 Dec 28, 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 723 Dec 26, 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 148 Dec 18, 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 399 Dec 23, 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 Dec 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