Package Exports
- node-mpv
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (node-mpv) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Node-MPV
A wrapper to comfortably use mpv player with node.js. It provides functions for the most of the commands needed to control the player. It's easy to use and highly flexible.
The module keeps an instance of mpv running in the background (using mpv's --idle) and communicates over the Json IPC API.
It also provides direct access to the IPC socket. Thus this module is not only limited to the methods it provides, but can fully communicate with the mpv API.
This module requires mpv to be installed on your system to work
For streaming playback such as YouTube and SoundCloud youtube-dl is required
Important
In version 0.13.0 the behaviour of mute() has changed. Use toggleMute() instead.
Install
npm install node-mpvOS X
brew install mpv youtube-dlLinux (Ubuntu/Debian)
sudo apt-get install mpv youtube-dlyoutube-dl is only required if you want to stream videos or music from YouTube, SoundCloud or other websites supported by youtube-dl. See here for a list of supported websites.
Usage
mpv = require('node-mpv');
mpvPlayer = new mpv();You optionally pass a Json object with options to the constructor. Possible options, along with their default values are the following
{
"audio_only": false,
"binary": null,
"debug": false,
"ipcCommand": null,
"socket": "/tmp/node-mpv.sock",
"time_update": 1,
"verbose": false,
}audio_onlywill add the--no-videoand--no-audio-displayargument and start mpv in audio only modebinarywill use the provied path to a mpv binary instead of using the one found in $PATHdebugprints error messagesipc_commandallows to set the ipc command to start the ipc socket. Possible options are --input-unix-socket and --input-ipc-server. This is usually not needed since Node-MPV is able to determine the correct command by itself, for the most partsocketspecifies the socket mpv openstime_updatethe time interval in seconds, how often mpv should report the current time position, when playing a titleverbosewill print various information on the console
You can also provide an optional second argument, an Array containing mpv command line options. A list of available arguments can be found in the documentation
mpvPlayer = new mpv({
"verbose": true,
"audio_only": true
},
[
"--fullscreen",
"--fps=60"
]);Mpv is then easily controllable via simple function calls.
mpvPlayer.loadFile("/path/to/your/favorite/song.mp3");
mpvPlayer.volume(70);Events are used to detect changes.
mpvPlayer.on('statuschange', function(status){
console.log(status);
});
mpvPlayer.on('stopped', function() {
console.log("Gimme more music");
});Methods
Load Content
loadFile (file, mode="replace")
Will load the
fileand starts playing it. This behaviour can be changed using themodeoptionreplace(default) replace current title and play the file immediatelyappendappends the title to the playlistappend-playappends the title to the playlist. If the playlist was empty this title is played
There is another
appendfunction in the playlist section, which can be used to append files and streams.loadStream (url)
Exactly the same as loadFile but loads a stream specified by
url, for example YouTube or SoundCloud.modeis the same as in loadFile.This function should be used to load YouTube and SoundCloud playlists, as loadPlaylist will not work with those.
Controlling MPV
play ()
Starts playback when in pause state
stop ()
Stops the playback entirely
pause ()
Pauses playback
resume ()
Resumes from pause mode
togglePause ()
Toggles the pause mode
mute ()
This methods behaviours has changed with version 0.13.0, use toggleMute() instead
Mutes the player
unmute ()
Unmute the player
toggleMute ()
Toggles between muted and unmuted
volume (volumeLevel)
Sets volume to
volumeLevel. Allowed values are between 0-100. All values above and below will just set the volume to 0 or 100 respectivelyadjustVolume (value)
Adjusts the volume with the specified
value. If this results in the volume going below 0 or above 100 it will be set to 0 or 100 respectivelyseek (seconds)
Will jump back or forth in the song for the specified amount of
seconds. Going beyond the duration of the song results in stop of playbackgoToPosition (seconds)
Jumps to the position specified by
seconds. Going beyond the boundaries of the song results in stop of playbackloop (times)
Loops the current title
timesoften. If set to "inf" the title is looped forever
Playlists
loadPlaylist (playlist, mode="replace")
Loads a playlist file.
modecan be one of the two folllowingThis function does not work with YouTube or SoundCloud playlists. Use loadFile or loadStream instead
replace(default) Replaces the old playist with the new oneappendAppends the new playlist to the active one
append (file, mode="append")
Appends
file(which can also be an url) to the playlist.append(default) Append the titleappend-playWhen the playlist was empty the title will be started
next (mode="weak")
Skips the current song.
modecan be one of the following twoweak(default) If the song is the last song in the playlist it is not skippedstrongThe song is skipped and playback is stopped
prev (mode="weak")
Skips the current song.
modecan be one of the following twoweak(default) If the song is the first song in the playlist it is not stoppedstrongThe song is skipped and playback is stopped
clearPlaylist ()
Clears the playlist
playlistRemove (index)
Removes the song at
indexfrom the playlist. Ifindexis set to "current" the current song is removed and playback stopsplaylistMove (index1, index2)
Moves the song at
index1to the position atindex2shuffle ()
Shuffles the play into a random order
Audio
addAudioTrack (file, flag, title, lang)
Adds an audio file to the video that is loaded.
fileThe audio file to loadflag(optional) Can be one of "select" (default), "auto" or "cached"title(optional) The name for the audio track in the UIlang(optional) the language of the audio track
flaghas the following effects- select - the added audio track is selected immediately
- auto - the audio track is not selected
- cached - select the audio track, but if a audio track file with the same name is already loaded, the new file is not added and the old one is selected instead
removeAudioTrack ()
Removes the audio track specified by
id. Works only for external audio tracksselectAudioTrack (id)
Selects the audio track associated with
idcycleAudioTracks ()
Cycles through the audio tracks
adjustAudioTiming (seconds)
Shifts the audio timing by
secondsspeed (scale)
Controls the playback speed by
scalewhich can take any value between 0.01 and 100If the
--auto-pitch-correctionflag (on by default) is used, this will not pitch the audio and uses a scaletempo audio filter
Video
fullscreen ()
Goes into fullscreen mode
leaveFullscreen ()
Leaves fullscreen mode
toggleFullscreen ()
Toggles between fullscreen and windowed mode
screenshot (file, option)
Takes a screenshot and saves it to
file.optionsis one of the followingsubtitles(default) Takes a screenshot including the subtitlesvideoOnly the image, no textswindowThe scaled mpv window
rotateVideo (degrees)
Rotates the video clockwise.
degreecan only be multiples of 90 and the rotation is absolute, not relativezoomVideo (factor)
Zooms into the video. 0 does not zoom at all, 1 zooms double and so on
brightness (value)
Sets the brightness to
value. Allowed values are between -100 and 100contrast (value)
Sets the contrast to
value. Allowed values are between -100 and 100saturation (value)
Sets the saturation to
value. Allowed values are between -100 and 100gamma (value)
Sets the gamma to
value. Allowed values are between -100 and 100hue (value)
Sets the hue to
value. Allowed values are between -100 and 100
Subtitles
addSubtilte (file, flag, title, lang)
Adds a subtitle file to the video that is loaded.
fileThe subtitle file to loadflag(optional) Can be one of "select" (default), "auto" or "cached"title(optional) The name for the subtitle file in the UIlang(optional) The language of the subtitle
flaghas the following effects- select - the added subtitle is selected immediately
- auto - the subtitle is not selected
- cached - select the subtitle, but if a subtitle file with the same name is already loaded, the new file is not added and the old one is selected instead
removeSubitlte (id)
Removes the subtitle file specified by
id. Works only for external subtitleselectSubitlte (id)
Selects the subtitle associated with
idcycleSubtitles ()
Cycles through all available subtitles
toggleSubtitleVisibility ()
Toggles between hidden and visible subtitle
showSubtitles ()
Shows the subtitle
hideSubtitles ()
Hides the subtitles
adjustSubtitleTiming (seconds)
Shifts the subtitle timing by
secondssubtitleSeek (lines)
Jumps as many lines of subtitles as defined by
lines. Can be negative. This will also seek in the video.subitlteScale (scale)
Adjust the scale of the subtitles
Properties
These methods can be used to alter properties or send arbitary commands to the running mpv player. Information about what commands and properties are available can be found in the list of commands and list of properties sections of the mpv documentation.
The most common commands are already covered by this modules API. This part enables you to send any command you want over the IPC. With this you are not limited the methods defined by this module.
setProperty (property, value)
Sets the specified
propertyto the specifiedvaluesetMultipleProperties (properties)
Calls setProperty for every property specified in the arguments Json object. For example
setMultipleProperties({ "volume": 70, "fullscreen": true });
getProperty (property, [id])
Gets information about the specified
property.If an
idis used, the answer comes via a getrequest event containing theidand theproperty.If no
idwas set this function returns a promise delivering theproperty. It can be used as in the example belowmpvPlayer.getProperty('duration').then(function(duration) { console.log("Duration: ", duration); });
addProperty (property, value)
Increased the
propertyby the specifiedvalue. Needless to say this can only be used on numerical properties. Negative values are possiblemultiplyProperty (property, value)
Multiply the specified
propertybyvaluecycleProperty (property)
Cycles the values of an arbitrary property
command (command, args)
Sends the
commandto the mpv player with the arguments specified inargsThe Json command`{"command": ["loadfile", "audioSong.mp3"]}`becomes a function call
`command("loadfile",["audioSong.mp3"]`freeCommand (command)
This will send an arbitrary command to the mpv player. It must however follow the specification of the Json IPC protocol. Its syntax can be found in the documentation.
A trailing "\n" will be added to the command.
Observing
observeProperty (property, id)
This will add the specified property to the statusupdate event which is emitted whenever one of the observed properties changes.
The Ids 0-12 are already taken by the properties which are observed by default.
unobserveProperty(id)
This will remove the property associated with the specified id from the statusupdate.
Unobserving default properties may break the module.
Events
The Node-MPV module provides various events to notify about changes of the mpv player's state.
started
Whenever mpv starts playing a song or video
stopped
Whenever the playback has stopped
paused
Whenever mpv was paused
resumed
Whenever mpv was resumed
timeposition <seconds>
When a song or video is currently playing and the playback is not paused, this event will emit the current position in seconds.
When creating the mpv instance you can set a parameter, how often this event should occur. Default is every second
getrequest <id, data>
Delivers the reply to a function call to the getRequest method
statuschange <status object>
Whenever the status of one of the observed properties changes, this event will be emitted providing the complete status object
By default various properties are already observed and the status object looks like the following
{ "mute": false, "pause": false, "duration": null, "volume": 100, "filename": null, "path": null, "media-title": null, "playlist-pos": 0, "playlist-count": 0, "loop": "no" }
If the player is running in video mode the following properties are present as well.
{ "fullscreen": false, "sub-visibility": false }
filenameWhen playing a local file this contains the filename. When playing for example a YouTube stream, this will only contain the trailing urlpathProvides the absolute path to the music file or the full url of a streammedia-titleIf available in the file this will contain the title. When streaming from YouTube this will be set to the video's nameThis object can expanded through the observeProperty method making it possible to watch any state you desire, given it is provided by mpv
Observing
node-mpv allows you to observe any property the mpv API offers you, by simply using the observeProperty function.
observeProperty(property, id);
This will add the property to status update object emitted by the statuschange event. Everytime that property changes such an event will be triggered.
By calling unobserveProperty(id) the property associated with that id is removed from the statuschange
By default node-mpv is already observing some useful properties by default.
{
"mute": Boolean,
"pause": Boolean,
"duration": Number,
"volume": Number,
"filename": String,
"path": String,
"media-title": String,
"playlist-pos": Number,
"playlist-count": Number,
"loop": Number // this one can be set to "inf" for endless looping
}If node-mpv is not run in audio_only mode the following two properties will be observed, too
{
"fullscreen": Boolean,
"sub-visibility": Boolean
}The IDs 0 - 12 are already used for the default properties. Unobserving them will most likely break the module.
For more information on the statuschange part, check the event section.
Bug with observing playlist-count
As of mpv version 0.17.0, the playlist-count property is not updated as one would expect. It is not updated on playlistRemove and append. I already filed an issue about that and the problem was already fixed. If you need this feature you will have to build and install mpv yourself. Instructions for that can be found on the projects GitHub page.
Example
var mpvAPI = require('./mpv.js');
var mpvPlayer = new mpvAPI();
// This will load and start the song
mpvPlayer.loadFile('/path/to/your/favorite/song.mp3');
// This will bind this function to the stopped event
mpvPlayer.on('stopped', function() {
console.log("Your favorite song just finished, let's start it again!");
mpvPlayer.loadFile('/path/to/your/favorite/song.mp3');
});
// Set the volume to 50%
mpvPlayer.volume(50);
// Stop to song emitting the stopped event
mpvPlayer.stop();Known Issues
IPC Command
The command line argument to start the IPC socket has changed in mpv version 0.17.0 from --input-unix-socket to --input-ipc-socket. This module uses regular expressions to find the version number from the mpv --version output. If mpv is compiled from source, the version number is stated as UNKNOWN and this module will assume, that you use the latest version and use the new command.
If you use self compiled version stating UNKNOWN as the version number below mpv version 0.17.0 you have to use the ipc_command option with '--input-unix-socket'.
To check this enter the following in your command shell
mpv --versionMPV Player 0.18.1
MPV Player version 0.18.1 has some issues that the player crashes sometimes, when sending commands through the ipc socket. If you're using version 0.18.0 try to use a newer (or older) version.
To check your version number enter the following in your command shell
mpv --versionChangelog
See changelog for more information or API breaking changes