๐Ÿ“น Framework to Play a Video in the Background of any UIView

Overview

Build Status codecov doccov Platform Swift MIT License CocoaPods Version Status Carthage compatible

SwiftVideoBackground is an easy to use Swift framework that provides the ability to play a video on any UIView. This provides a beautiful UI for login screens, or splash pages, as implemented by Spotify and many others.

Features

  • Play a video with one line of code
  • Supports local videos && videos from a web URL
  • Automatically adjusts when device orientation changes
  • Automatically resumes video when app re-enters foreground
  • Pause, resume, restart, and other controls
  • Loop videos (optional)
  • Mute sound (optional)
  • Darken videos so overlying UI stands out more (optional)
  • Documentation

Contents

  1. Integration
  2. Migration Guide
  3. Usage
  4. License
  5. Authors

Integration

CocoaPods

You can use CocoaPods to install SwiftVideoBackground by adding it to your Podfile:

For Swift 5:

pod 'SwiftVideoBackground'

For Swift 4:

pod 'SwiftVideoBackground', '~> 3.0'

For Swift 3:

pod 'SwiftVideoBackground', '0.06'

Carthage

You can use Carthage to install SwiftVideoBackground by adding it to your Cartfile:

github "dingwilson/SwiftVideoBackground"

Manually

To use this library in your project manually you may:

  1. for Projects, just drag VideoBackground.swift to the project tree
  2. for Workspaces, include the whole SwiftVideoBackground.xcodeproj

Migration Guide

Version 3.0.0

Version 2.0.0

See the quick migration guide.

Usage

Example

import UIKit
import SwiftVideoBackground

class MyViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    try? VideoBackground.shared.play(view: view, videoName: "myVideo", videoType: "mp4")

    /* or from URL */

    let url = URL(string: "https://coolVids.com/coolVid.mp4")!
    VideoBackground.shared.play(view: view, url: url)
  }
}

Documentation for Version 0.06 (Swift 3) can be found here.

Customization

play() has four additional optional parameters for customization:

  • darkness: CGFloat - Value between 0 and 1. The higher the value, the darker the video. Defaults to 0.
  • isMuted: Bool - Indicates whether video is muted. Defaults to true.
  • willLoopVideo: Bool - Indicates whether video should restart when finished. Defaults to true.
  • setAudioSessionAmbient: Bool - Indicates whether to set the shared AVAudioSession to ambient. If this is not done, audio played from your app will pause other audio playing on the device. Defaults to true.

So for example:

VideoBackground.shared.play(
    view: view,
    videoName: "myVideo",
    videoType: "mp4",
    darkness: 0.25,
    isMuted: false,
    willLoopVideo: true,
    setAudioSessionAmbient: true
)

-> will play the video with the sound on, slightly darkened, continuously looping, and without affecting other sources of audio on the device.

Any combination of the parameters can be included or left out.

setAudioSessionAmbient only has an effect in iOS 10.0+. For more information, see the docs.

Controls

  • pause() - Pauses the video.
  • resume() - Resumes the video.
  • restart() - Restarts the video.
  • getThumbnailImage(from: URL, at: CMTime) - Generate an image from the video to show as thumbnail.
  • darkness - Change this CGFloat to adjust the darkness of the video. Value 0 to 1. Higher numbers are darker. Setting to an invalid value does nothing.
  • isMuted - Change this Bool to mute/unmute the video.
  • willLoopVideo - Change this Bool to set whether the video restarts when it ends.
  • videoGravity - Default is .resizeAspectFill. Change to .resizeAspect (doesn't fill view) or .resize (doesn't conserve aspect ratio).
  • playerLayer - The AVPlayerLayer that can be accessed for advanced control and customization of the video.

Singleton

SwiftVideoBackground includes a singleton instance that can be conveniently accessed with VideoBackground.shared. An instance of VideoBackground can only play one video on one UIView at a time. So if you need to play on multiple UIViews, you need to retain an instance of VideoBackground for each UIView:

let videoBackground1 = VideoBackground()

Adding Videos To Your Project

In order to play local videos, you must add them to your project:

  1. Open project navigator
  2. Select your target
  3. Select Build Phases
  4. Select Copy Bundle Resources
  5. Click + to add a video

add video to project

License

SwiftVideoBackground is released under an MIT License. See LICENSE for details.

Authors

Wilson Ding, Quan Vo

Copyright ยฉ 2016-present Wilson Ding.

Please provide attribution, it is greatly appreciated.

Comments
  • BREAKING CHANGE: Add several controls. Remove multi vid support.

    BREAKING CHANGE: Add several controls. Remove multi vid support.

    What does this PR do?

    - added new APIs under `UIView` extension. Videos can now be played with: - `myView.playVideo(videoName:videoType)` - `alpha`, `isMuted`, & `willLoopVideo` can be changed at runtime with: - `myView.setVideoAlpha(_:)` etc - added `pauseVideo()` & `resumeVideo()` - the `VideoBackground` class is no longer needed: - the settings, state observers, etc for a view are automatically managed under the covers through other means - old APIs are still usable, but deprecation warnings added - removed multi vid support for now (migrating this feature to the new structure would have been a lot of work)* - added docs - profiled

    *I could make this a non breaking PR by implementing this. Doable.

    TODO:

    • more testing with changing alpha, isMuted, etc.
    • clean up example view controller and storyboard (currently using them to test stuff, ignore ftm)
    • update README

    Large PR so review incrementally at your leisure. Also let me know if I've gotten any of the devops syntax/etc wrong.

    • add support for playing video from web URL
    • add APIs for pause, restart, resume, alpha, isMuted, & willLoopVideo
    • ~~will try to implement merging~~ remove multi vid support
    • beefed up example
    • add #32
    • add docs
    • update README

    TODO:

    • [x] add stuff to README regarding false positive memory leak on simulator with vids with sound
    • [x] add recommendation to use FFMPEG to merge vids
    • [x] flesh out tests #50
    • [x] deprecate alpha APIs
    • [x] change alpha to darkness

    What issues (if any) are related to this PR? Or why was this change introduced?

    Closes #23 Closes #31 Closes #32 Closes #50 Closes #52 Closes #54

    Checklist

    • [x] Does this contain code changes?
    • [x] Does this have tests?
    • [x] Does this have documentation?
    • [x] Does this break the public API (Requires major version bump)?
    • [x] Is this a new feature (Requires minor version bump)?
    opened by quanvo87 25
  • 2.0

    2.0

    Opening PR now to begin code review. Will update README and jazzy when rdy.

    Tested on my other app.

    Example usage of new API would be:

    import UIKit
    import BackgroundVideo
    
    class MyViewController: UIViewController {
      private let backgroundVideo = BackgroundVideo()
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        backgroundVideo.play(view: view, videoName: "worldstar", videoType: "mp4")
      }
    }
    

    play() has three additional optional parameters:

    • isMuted: defaults to true
    • opacity: defaults to 1.0
    • loopVideo: defaults to true

    One caveat of this approach is that if the user wants the video to loop, they need to declare an instance of BackgroundVideo in such a way that it's retained for the life of the UIView they want it to play on (like in the example above). If it's just declared in a function, the instance gets deallocated as soon as the function ends and the notification center cannot alert it to repeat the video.


    I also think some work needs to be done regarding the audio. Right now, even when muted, if the user is listening to music on the their phone, then opens the app using this API, their audio will be "dampened".

    opened by quanvo87 12
  • Issue with rotation

    Issue with rotation

    If I rotate my iPad the video doesn't adapt to the screen size (please check GIF: https://giphy.com/gifs/l4pSVnVwldE37HkuQ). Is there any way I can fix this?

    bug 
    opened by csr 11
  • Updated README with FFmpeg blog post and fixed typos

    Updated README with FFmpeg blog post and fixed typos

    What does this PR do?

    Updates README with link to FFmpeg blog post

    What issues (if any) are related to this PR? Or why was this change introduced?

    Closes #56

    Checklist

    • [ ] Does this contain code changes?
    • [ ] Does this have tests?
    • [ ] Does this have documentation?
    • [ ] Does this break the public API (Requires major version bump)?
    • [ ] Is this a new feature (Requires minor version bump)?
    opened by dingwilson 10
  • Crash on cleanUp

    Crash on cleanUp

    https://github.com/dingwilson/SwiftVideoBackground/blob/78cbe752332dfa3766a899ff794fbd567e355b5c/SwiftVideoBackground/Sources/VideoBackground.swift#L181

    Crashes on above line due to the superview of that view being nil sometimes

    opened by ndemie 8
  • add pause and resume

    add pause and resume

    Scenario:

    • a video is being played on a UIView
    • that UIView becomes hidden (ie another view controller is pushed onto the stack)
    • that UIView becomes un-hidden again (ie previously mentioned view controller is closed)

    What happens: It seems that while UIView was hidden, the video wasn't playing, and when it gets un-hidden, it plays the video super fast, up to the point that it would be if it wasn't paused.

    Not sure if that makes sense or if that's actually what's happening, but I know there is some super fast video playing after a hidden/un-hidden scenario.

    I think a fix would be to implement pause() and resume(). I'm hoping correctly using these methods when you expect your view to be hidden/un-hidden fixes this.

    This might also be able to be automated if desired (not sure if possible, not sure of side effects).

    opened by quanvo87 8
  • Changing video.

    Changing video.

    Hello, I'm trying to use this for onboarding videos. As the user hits next I would like to change the video using the same view. Anyway to do this with this plugin? It currently just stays the same video even though I'm trying to update it when the user hits next.

    Thanks!

    opened by gilosborne 7
  • Added example project, basic tests, and CodeCov

    Added example project, basic tests, and CodeCov

    Closes #28 Closes #49

    Make sure to squash and merge the commits

    Tasks:

    • [x] Add example project
    • [x] Move source files to Sources/ folder
    • [x] Ensure jazzy docs don't pick up files from example project
    • [ ] Ensure this doesn't break Cocoapods
    • [ ] Ensure this doesn't break Carthage
    • [x] Add tests
    • [x] Add Codecov Integration (#49)
    opened by dingwilson 6
  • Playing different videos on each UITableViewCell

    Playing different videos on each UITableViewCell

    Hi @dingwilson , I'm trying to create a tableView with each cell has a separate video. Assuming that the tableView cells are only 2 for the below code Video string is placed in a static array and instances of VideoBackground

    var videoArray = ["video1", "video2", "video3", "video4", "video5"] let videoBackground1 = VideoBackground() let videoBackground2 = VideoBackground()

    and inside the cellforRow indexPath method (which is weird for me, but don't know where to place, where a UIView is placed inside the cell.

    if indexPath.row == 0{ try? videoBackground1.play(view: cell.videoView, videoName: videoArray[0], videoType: "mp4", isMuted: false) }else if indexPath.row == 1 { try? videoBackground2.play(view: cell.videoView, videoName: videoArray[1], videoType: "mp4", isMuted: false) }

    In above case, the vice is not playing or showing, so when replacing the instance with the singleton, it's showing the last cell only due to the single AVPlayer instance.

    opened by MohdElBasyouni 5
  • configurable videoGravity, caching, and thumbnail image

    configurable videoGravity, caching, and thumbnail image

    What does this PR do?

    These are several features we need in a project:

    • changing the default videoGravity
    • caching videos from remote URLs
    • creating thumbnail image from a video

    What issues (if any) are related to this PR? Or why was this change introduced?

    No issues, just enhancements.

    Checklist

    • [x] Does this contain code changes?
    • [ ] Does this have tests?
    • [x] Does this have documentation?
    • [x] Does this break the public API (Requires major version bump)?
    • [x] Is this a new feature (Requires minor version bump)?
    opened by yonat 4
  • Dependency

    Dependency "SwiftVideoBackground" has no shared framework schemes for any of the platforms: iOS

    When installing with carthage using github "dingwilson/SwiftVideoBackground" and then running:

    carthage update --platform iOS
    

    The process fails with:

    Dependency "SwiftVideoBackground" has no shared framework schemes for any of the platforms: iOS

    I tried with both carthage 0.28.0 and 0.29.0 with the same problem. Not sure what the issue is, but a solution on stack overflow talks about needing the proper targets in xcshareddata/xcschemes/.xcscheme.

    If you compare your single scheme to say Alamofire's https://github.com/Alamofire/Alamofire/tree/master/Alamofire.xcodeproj/xcshareddata/xcschemes maybe this provides a clue?

    bug 
    opened by sjmueller 4
  • How to define that video from Web is loading and how can i display it to user?

    How to define that video from Web is loading and how can i display it to user?

    Hi, your library is cool. However, i would like to know how to track that video from Web is loading? I want to show to user something like loading spinner during the video loading.

    opened by IKorabel 1
  • Url to pull video stream in the background?

    Url to pull video stream in the background?

    let url = URL(string: "https://viewer.millicast.com/v2?streamId=w9dvKs/kkmy5gxc")! VideoBackground.shared.play(view: view, url: url)

    So i have the above code in my viewDidLoad(), and for the videos it works great. However, I want to pull from a live stream and display it, but it always is a blank screen even though the stream is working. Would you have any ideas on how to resolve that issue or is it maybe on the streams end?

    Kind regards, Andrew Bolt

    opened by BoltAlot2 1
  • How do you access the video layer?

    How do you access the video layer?

    I'm trying to figure out how to access the video layer so I can do some animation on it.

    The doc says playerLayer is the layer. but how do I use this in my code?

    I've tried this and it does work:

    let playerLayer = VideoBackground()

    and

    let playerLayer = AVPlayerLayer()

    any help would be appreciated.

    opened by phiasco12 0
  • cannot play video saved into phone storage

    cannot play video saved into phone storage

    Dear sir, Thanks so much for the Ince library. Currently I am trying too play mp4 files that is saved into phone storage. I cannot run it. My code is :

    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] print(documentsDirectory)

        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
           let url = NSURL(fileURLWithPath: path)
           if let pathComponent = url.appendingPathComponent("water.mp4") {
               let filePath = pathComponent.path
               let fileManager = FileManager.default
               if fileManager.fileExists(atPath: filePath) {
                   print("FILE AVAILABLE")
                let url = URL(string: filePath)!
                videoBackground1.play(view: view1, url: url, darkness: 0.1)
                
               } else {
                   print("FILE NOT AVAILABLE")
               }
           } else {
               print("FILE PATH NOT AVAILABLE")
           }
    

    below is debug code:FILE AVAILABLE 2021-01-07 22:48:54.253683+0200 yarab[18271:807739] [plugin] AddInstanceForFactory: No factory registered for id <CFUUID 0x600003c5d3e0> F8BB1C28-BAE8-11D6-9C31-00039315CD46 2021-01-07 22:48:54.299434+0200 yarab[18271:807835] NSURLConnection finished with error - code -1002

    opened by waleedmakarem 1
Releases(3.3.0)
Owner
Wilson Ding
I build cool stuff people use @amzn | formerly @limebike @IBM-Swift
Wilson Ding
โ–ถ๏ธ 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
An iOS application ๐Ÿ“ฑ that extracts text real time using camera ๐Ÿ“ท and play relevant video from the text

CHARUSAT-SceW It is an iOS application ?? that scans and extracts text real-time through camera ?? , if it is detected. It will play relevent video fr

Vatsal Patel 2 Nov 15, 2021
How to Display Video from URL inside custom design UIView

Technicalisto How to Display Video from URL inside custom design UIView Add your UIView and connect it . Add This method for display func DisplayVideo

Aya Baghdadi 1 Jun 24, 2022
A fully functional short video app project.Record a six secends video while playing prank sounds.

prankPro A fully functional short video app project How to Install 1. use coconapod to init your xcode environment. 2. change the app-keys in `applica

huijimuhe 258 Jun 19, 2022
JDVideoKit - You can easily transfer your video into Three common video type.

JDVideoKit Introduction You can easily transfer your video into Three common video type. You can use set up camera easily. Installation pod 'JDVideoK

้ƒญไป‹้จต 24 Sep 9, 2021
A Swift library to upload video files to api.video platform.

api.video IOS video uploader api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and manag

api.video 7 Dec 9, 2022
Video mp4 record save display - How to Take , Save and Display a .mp4 Video

Technicalisto How to Take , Save and Display a .mp4 Video Add your design with v

Aya Baghdadi 2 Aug 7, 2022
api.video is the video infrastructure for product builders

api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in your app.

api.video 4 Jun 27, 2022
YouTubePlayerKit A Swift Package to easily play YouTube videos ๐Ÿ“บ

A Swift Package to easily play YouTube videos ??

Sven Tiigi 304 Jan 7, 2023
A lightweight app to play videos from the Files app in a better (dark) interface which avoids losing your playback position.

Playerly Playerly is a very lightweight Swift app that allows you to select a file (video or movie) from the built in Document Browser, and play it in

Julian Schiavo 28 Dec 3, 2022
Audio player demo based on Swift and SwiftUI, which can play local or network audio.

SwiftAudioDemo Audio player demo based on Swift and SwiftUI, which can play local or network audio. In this demo, I have made a radio player to play n

Jensen Zhang 6 Mar 13, 2022
A video composition framework build on top of AVFoundation. It's simple to use and easy to extend.

A high-level video composition framework build on top of AVFoundation. It's simple to use and easy to extend. Use it and make life easier if you are implementing video composition feature.

VideoFlint 1.4k Dec 25, 2022
High-performance and flexible video editing and effects framework, based on AVFoundation and Metal.

High-performance and flexible video editing and effects framework, based on AVFoundation and Metal.

BearRuan 650 Dec 30, 2022
Swift Package used for video where I demonstrate how to extract a package to a local framework and modify it.

SegmentedPicker NOTE: This sample code is taken from the article by Frank Jia in his article titled Build a Custom iOS Segmented Control With SwiftUI

Stewart Lynch 1 Oct 11, 2021
โ€‹ This framework allows developers to quickly manipulate audio and video splicing operations.

MTrack This framework allows developers to quickly manipulate audio and video splicing operations.We welcome your feedback in issues and pull requests

null 1 Nov 15, 2021
A SwiftUI framework which makes it easy to integrate Video Call and Chat within a few lines of code.

Welcome to iStream! This SwiftUI Framework allows you to add Video Call and Chat to your project within a few lines of code. To use this Framework, yo

null 2 Aug 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 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
A set of tools to trim, crop and select frames inside a video

PryntTrimmerView A set of tools written in swift to crop and trim videos. Example To run the example project, clone the repo, and run pod install from

Henry Huck 742 Jan 5, 2023