• Stars
    star
    662
  • Rank 68,103 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple, robust, blazing-fast YouTube Player API

yt-player ci npm downloads javascript style guide

Simple, robust, blazing-fast YouTube Player API

This package is used on Play.cash.

Install

npm install yt-player

If you do not use a bundler, you can use the standalone script directly in a <script> tag.

Why this package?

Most of the existing YouTube API packages on npm are incomplete or overcomplicated.

Note: It is irresponsible to publish a package that requires all of babel-runtime, lodash, and 20KB of other nonsense to do a simple task. Using fancy dependencies doesn't make you a better programmer, and it's certainly not a "best practice" to ship tons of extra code to your website visitors. Less is more. ๐Ÿ”ฅ

Features

  • Powered by the YouTube IFrame Player API
  • Lightweight - only 3.14kb gzipped and minified!
  • Extremely fast time-to-first-frame
    • YouTube IFrame API <script> is automatically loaded on first use
    • For even faster start time, add <script src='https://www.youtube.com/iframe_api' async></script> to your page
    • Automatically detects the presence of the API <script> so API is never loaded twice
  • API commands are automatically queued (until both the Iframe API and Player instance are ready)
  • Differentiate between fatal errors and unplayable video errors
  • Adds the all-important 'timeupdate' event, which the YouTube API lacks
  • Well-commented codebase makes it easy to understand what's going on
  • No large dependencies or unused code
  • Note: no support for old browsers (e.g. IE11 and below)

Usage

const YTPlayer = require('yt-player')
const player = new YTPlayer('#player')

player.load('GKSRyLdjsPA')
player.setVolume(100)

player.on('playing', () => {
  console.log(player.getDuration()) // => 351.521
})

API

player = new YTPlayer(element, [opts])

Create a new YouTube player. The player will take the place of the HTML element element. Alternatively, element can be a selector string, which will be passed to document.querySelector().

Examples: #player, .youtube-player, or a DOM node.

Optionally, provide an options object opts to customize the player.

opts.width (number)

This parameter indicates the width of the player.

opts.height (number)

This parameter indicates the height of the player.

opts.autoplay (boolean)

This parameter indicates whether the initial video will automatically start to play when the player loads. The default value is false.

opts.captions (string/boolean)

This parameter indicates the language of the closed captions that should be shown. The default behavior is based on user preference. The parameter value is an ISO 639-1 two-letter language code or a fully specified locale. Or, set to false to force captions to be disabled, ignoring the user preference.

opts.controls (boolean)

This parameter indicates whether the video player controls are displayed. The default value is true.

opts.keyboard (boolean)

This parameter indicates whether the player will respond to keyboard shortcuts. The default value is true.

opts.fullscreen (boolean)

This parameter indicates whether the player will show a fullscreen button. The default value is true.

opts.annotations (boolean)

This parameter indicates whether the player will show video annotations. The default value is true.

opts.modestBranding (boolean)

This parameter lets you use a YouTube player that does not show a YouTube logo. Even when this option is enabled, a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player. The default value is false.

opts.related (boolean)

This parameter indicates whether the player should show related videos from the same channel (false) or from any channel (true) when playback of the video ends. The default value is true.

opts.timeupdateFrequency (number)

The time between onTimeupdate callbacks, in milliseconds. Default is 1000.

See: YT.Player parameters and playerVars parameters for additional documentation about these parameters.

opts.playsInline (boolean)

This parameter controls whether videos play inline or fullscreen in an HTML5 player on iOS. Default is true.

opts.start (number)

This parameter causes the player to begin playing the video at the given number of seconds from the start of the video. The parameter value is a positive integer. Note that the player will look for the closest keyframe to the time you specify. This means that sometimes the play head may seek to just before the requested time, usually no more than around two seconds. Default is 0.

opts.host (string)

This parameter controls the hostname that videos are loaded from. Set to 'https://www.youtube-nocookie.com' for enhanced privacy. The default value is 'https://youtube.com'.

player.load(videoId, [autoplay, [start]])

This function loads the specified videoId. An example of a videoId is 'GKSRyLdjsPA'.

Optionally, specify an autoplay parameter to indicate whether the video should begin playing immediately, or wait for a call to player.play(). Default is false. The optional start parameter accepts a float/integer. If it is specified, then the video will start from the closest keyframe to the specified time.

This should be the first function called on a new Player instance.

player.play()

Plays the currently loaded video.

player.pause()

Pauses the currently loaded video.

player.stop()

Stops and cancels loading of the current video. This function should be reserved for rare situations when you know that the user will not be watching additional video in the player. If your intent is to pause the video, you should just call pause(). If you want to change the video that the player is playing, you can call load() without calling stop() first.

player.seek(seconds)

Seeks to a specified time in the video. If the player is paused when the function is called, it will remain paused. If the function is called from another state (playing, video cued, etc.), the player will play the video. The player will advance to the closest keyframe before that time unless the player has already downloaded the portion of the video to which the user is seeking.

player.setVolume(volume)

Sets the volume. Accepts an integer between 0 and 100.

player.getVolume()

Returns the player's current volume, an integer between 0 and 100. Note that getVolume() will return the volume even if the player is muted.

player.mute()

Mutes the player.

player.unMute()

Unmutes the player.

player.isMuted()

Returns true if the player is muted, false if not.

player.setSize(width, height)

Sets the size in pixels of the <iframe> that contains the player.

player.setPlaybackRate(rate)

This function sets the suggested playback rate for the current video. If the playback rate changes, it will only change for the video that is already being played. Calling load() will reset the playback rate to 1.

player.setPlaybackQuality(suggestedQuality)

This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the 'playbackqualitychange' event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function.

The suggestedQuality parameter value can be 'small', 'medium', 'large', 'hd720', 'hd1080', 'highres' or 'default'. We recommend that you set the parameter value to 'default', which instructs YouTube to select the most appropriate playback quality, which will vary for different users, videos, systems and other playback conditions.

If you call the setPlaybackQuality function with a suggestedQuality level that is not available for the video, then the quality will be set to the next lowest level that is available. In addition, setting suggestedQuality to a value that is not a recognized quality level is equivalent to setting suggestedQuality to 'default'.

player.getPlaybackRate()

This function retrieves the playback rate of the currently playing video. The default playback rate is 1, which indicates that the video is playing at normal speed. Playback rates may include values like 0.25, 0.5, 1, 1.5, and 2.

player.getAvailablePlaybackRates()

This function returns the set of playback rates in which the current video is available. The default value is 1, which indicates that the video is playing in normal speed.

The function returns an array of numbers ordered from slowest to fastest playback speed. Even if the player does not support variable playback speeds, the array should always contain at least one value (1).

player.getDuration()

Returns the duration in seconds of the currently playing video. Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just before the video starts playing.

player.getProgress()

Returns a number between 0 and 1 that specifies the percentage of the video that the player shows as buffered.

player.getState()

Returns the state of the player. Possible values are: 'unstarted', 'ended', 'playing', 'paused', 'buffering', or 'cued'.

player.getCurrentTime()

Returns the elapsed time in seconds since the video started playing.

player.destroy()

Removes the <iframe> containing the player and cleans up all resources.

player.destroyed (boolean)

Returns true if destroy() has been called on the player.

player.videoId (string)

Returns the currently loaded video ID, i.e. what was passed to load().

player.on('error', (err) => {})

This event fires if a fatal error occurs in the player. This does not include videos that fail to play, for whatever reason.

player.on('unplayable', (videoId) => {})

This event fires if the YouTube player cannot play the given video. This is not a fatal error. This event is reported separately from the 'error' event so there is an opportunity to play another video gracefully.

Possible reasons for this error:

  • The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.

  • The owner of the requested video does not allow it to be played in embedded players.

  • The request contains an invalid parameter value. For example, this error occurs if you specify a videoId that does not have 11 characters, or if the videoId contains invalid characters, such as exclamation points or asterisks.

player.on('timeupdate', (seconds) => {})

This event fires when the time indicated by the getCurrentTime() method has been updated.

player.on('unstarted', () => {})

player.on('ended', () => {})

player.on('playing', () => {})

player.on('paused', () => {})

player.on('buffering', () => {})

player.on('cued', () => {})

These events fire when the player enters the respective state. These event names are the same as the possible return values from player.getState().

When the player first loads a video, it will broadcast an unstarted event. When a video is cued and ready to play, the player will broadcast a cued event.

player.on('playbackQualityChange', (quality) => {})

This event fires whenever the video playback quality changes. Possible values are: 'small', 'medium', 'large', 'hd720', 'hd1080', 'highres'.

player.on('playbackRateChange', (playbackRate) => {})

This event fires whenever the video playback rate changes.

License

MIT. Copyright (c) Feross Aboukhadijeh.

More Repositories

1

simple-peer

๐Ÿ“ก Simple WebRTC video, voice, and data channels
JavaScript
7,405
star
2

SpoofMAC

๐Ÿ’ผ Change your MAC address for debugging
Python
3,028
star
3

thanks

๐Ÿ™Œ Give thanks to the open source maintainers you depend on! โœจ
JavaScript
2,768
star
4

buffer

The buffer module from node.js, for the browser.
JavaScript
1,772
star
5

spoof

Easily spoof your MAC address in macOS, Windows, & Linux!
JavaScript
1,771
star
6

awesome-mad-science

Delightful npm packages that make you say "wow, didn't know that was possible!"
1,124
star
7

filldisk.com

๐Ÿ’พ Masterful trolling with HTML5 localStorage
HTML
910
star
8

hostile

Simple, programmatic `/etc/hosts` manipulation (in node.js)
JavaScript
777
star
9

TheAnnoyingSite.com

The Annoying Site a.k.a. "The Power of the Web Platform"
JavaScript
727
star
10

clipboard-copy

Lightweight copy to clipboard for the web
JavaScript
585
star
11

bitmidi.com

๐ŸŽน Listen to free MIDI songs, download the best MIDI files, and share the best MIDIs on the web
JavaScript
507
star
12

electron-workshop

Workshop: Build cross-platform desktop apps with Electron
JavaScript
492
star
13

drag-drop

HTML5 drag & drop for humans
JavaScript
490
star
14

simple-get

Simplest way to make http get requests. Supports HTTPS, redirects, gzip/deflate, streams in < 100 lines
JavaScript
396
star
15

md5-password-cracker.js

Crack MD5 passwords with JavaScript Web Workers
JavaScript
381
star
16

run-parallel

Run an array of functions in parallel
JavaScript
363
star
17

magickeyboard.io

Ultimate hacker keyboard
JavaScript
339
star
18

safe-buffer

Safer Node.js Buffer API
JavaScript
338
star
19

timidity

Play MIDI files in the browser w/ Web Audio, WebAssembly, and libtimidity
Shell
315
star
20

p2p-graph

Real-time P2P network visualization with D3
JavaScript
286
star
21

multistream

A stream that emits multiple other streams one after another (streams3)
JavaScript
283
star
22

zelda

Automatically `npm link` all your packages together!
JavaScript
280
star
23

run-series

Run an array of functions in series
JavaScript
240
star
24

funding

Let's get open source maintainers paid โœจ
JavaScript
209
star
25

render-media

Intelligently render media files in the browser
JavaScript
199
star
26

cs253.stanford.edu

CS 253 Web Security course at Stanford University
JavaScript
194
star
27

simple-websocket

Simple, EventEmitter API for WebSockets
JavaScript
184
star
28

queue-microtask

fast, tiny `queueMicrotask` shim for modern engines
JavaScript
172
star
29

last-fm

Simple, robust LastFM API client (for public data)
JavaScript
169
star
30

studynotes.org

โœ๏ธ Learn faster. Study better.
JavaScript
159
star
31

whiteboard

P2P Whiteboard powered by WebRTC and WebTorrent
JavaScript
154
star
32

ytinstant.com

Real-time YouTube video surfing.
JavaScript
148
star
33

mediasource

MediaSource API as a node.js Writable stream
JavaScript
138
star
34

chrome-net

Use the Node `net` API in Chrome Apps
JavaScript
134
star
35

login-with-twitter

Login with Twitter. OAuth without the nonsense.
JavaScript
123
star
36

cross-zip

Cross-platform .zip file creation
JavaScript
120
star
37

Fullscreen-API-Attack

Demo of phishing attack on the native HTML5 full screen API.
JavaScript
116
star
38

unmute-ios-audio

Enable/unmute WebAudio on iOS, even while mute switch is on
JavaScript
113
star
39

capture-frame

Capture video screenshot from a `<video>` tag (at the current time)
JavaScript
113
star
40

ieee754

Read/write IEEE754 floating point numbers from/to a Buffer or array-like object.
JavaScript
111
star
41

cyberhobo

Offline `git push` and `npm publish` for cyberhobos
JavaScript
111
star
42

Instant.fm

Share music playlists with friends.
JavaScript
108
star
43

available

Scan npm for available package names
JavaScript
100
star
44

bg-sound

Web Component to emulate the old-school <bgsound> HTML element
JavaScript
95
star
45

lxjs-chat

Talk to strangers! (P2P video chat using WebRTC)
JavaScript
94
star
46

play.cash

๐ŸŽถ Music lovers, rejoice.
JavaScript
93
star
47

reddit

Simple Reddit API client
JavaScript
90
star
48

is-buffer

Determine if an object is a Buffer
JavaScript
89
star
49

run-waterfall

Run an array of functions in series, each passing its results to the next function
JavaScript
89
star
50

run-auto

Determine the best order for running async functions, LIKE MAGIC!
JavaScript
86
star
51

WireSheep

WireSheep shows you each user on the network and all the HTTP requests they're making in a pretty News Feed, a la Facebook.
C++
84
star
52

oculus-drone

Pilot a Parrot AR Drone with the Oculus Rift virtual reality headset!
C
81
star
53

arch

Better `os.arch()` for node and the browser -- detect OS architecture
JavaScript
79
star
54

string-to-stream

Convert a string into a stream (streams2)
JavaScript
79
star
55

feross.org

Pure concentrated awesome (a.k.a. my blog)
HTML
78
star
56

config

Server config files (nginx, mysql, certbot)
HTML
78
star
57

run-parallel-limit

Run an array of functions in parallel, but limit the number of tasks executing at the same time
JavaScript
76
star
58

blob-to-buffer

Convert a Blob to a Buffer.
JavaScript
72
star
59

CMSploit

Security scanner to find temporary config files that contain passwords on public websites
CoffeeScript
70
star
60

location-history

Lightweight browser location history abstraction
JavaScript
69
star
61

fromentries

Object.fromEntries() ponyfill (in 6 lines)
JavaScript
66
star
62

typedarray-to-buffer

Convert a typed array to a Buffer without a copy.
JavaScript
65
star
63

speakeasyjs.com

The JavaScript meetup for ๐Ÿฅผ mad science, ๐Ÿง™โ€โ™‚๏ธ hacking, and ๐Ÿงช experiments
JavaScript
64
star
64

express-sitemap-xml

Serve sitemap.xml from a list of URLs in Express
JavaScript
63
star
65

beepbeep

Make a console beep sound.
JavaScript
62
star
66

connectivity

Detect if the network is up (do we have connectivity?)
JavaScript
60
star
67

stream-to-blob

Convert a Readable Stream to a Blob
JavaScript
59
star
68

color-scheme-change

Detect system color scheme changes on the web (Dark Mode)
JavaScript
58
star
69

conferences

Conferences that I will attend or have already attended
53
star
70

Life

An experiment in treating life like a software project.
50
star
71

git-pull-or-clone

Ensure a git repo exists on disk and that it's up-to-date
JavaScript
50
star
72

cctv.js

Watch live visitors using your website.
JavaScript
48
star
73

Facebook-Like-Everything

Bookmarklet to Like every post+comment that you see on Facebook.
JavaScript
47
star
74

load-script2

Dynamic script loading for modern browsers
JavaScript
46
star
75

simple-sha256

Generate SHA-256 hashes (in Node and the Browser)
JavaScript
45
star
76

async-lru

A simple async LRU cache supporting O(1) set, get and eviction of old keys
JavaScript
45
star
77

peerdb

JavaScript
44
star
78

dotfiles

Configuration files for zsh, screen, git, ssh, sublime, dot dot dot
Shell
39
star
79

chrome-dgram

Use the Node `dgram` API in Chrome Apps
JavaScript
39
star
80

webcam-spy

Demo of Adobe Flash clickjacking vulnerability to spy on a user's webcam.
JavaScript
39
star
81

standard-react

JavaScript Standard Style for React Users
JavaScript
36
star
82

BrainGrinder

Instant foreign language flashcards (with audio!)
CSS
34
star
83

ahh-windows

Windows XP Emulator -- in the browser :)
HTML
34
star
84

chrome-dns

Use the Node `dns` API in Chrome Apps
JavaScript
34
star
85

objection-slug

Automatically generate slugs for an Objection.js model
JavaScript
33
star
86

call-log

Instrument a JavaScript class (or object) so that anytime a method function is called it gets logged to the console.
JavaScript
33
star
87

zero-fill

Zero-fill a number to the given size.
JavaScript
31
star
88

caught-in-a-web-of-apis

Attack code to accompany "Caught in a Web of APIs: An Analysis of Powerful Web APIs" research paper
JavaScript
30
star
89

cache-chunk-store

In-memory LRU (least-recently-used) cache for abstract-chunk-store compliant stores
JavaScript
28
star
90

clash

A Simple Bash-Like Shell
C++
28
star
91

preload-img

Preload an image on a webpage
JavaScript
26
star
92

chunk-store-stream

Convert an abstract-chunk-store compliant store into a readable or writable stream
JavaScript
26
star
93

feross-card

It's me, Feross!
JavaScript
24
star
94

vlc-command

Find VLC player command line path
JavaScript
24
star
95

raft

An understandable consensus algorithm
C++
23
star
96

simple-concat

Super-minimalist version of `concat-stream`. Less than 15 lines!
JavaScript
23
star
97

stream-to-blob-url

Convert a Readable Stream to a Blob URL
JavaScript
23
star
98

SuperTranslate

"Super translate" words into many different languages at once
CSS
21
star
99

Fling

Send songs, videos, web urls from your phone to your desktop with a flick of your wrist
Objective-C
21
star
100

detect-proxy

Using <img> to detect whether the user is browsing through a proxy or not.
21
star