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
This module keeps an instance of mpv player running in the background and communicates over the Json IPC API.
It provides functions for the most of the commands needed to control mpv. It's easy to use and highly flexible.
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
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
Simply create an instance of the player
mpv = require('node-mpv');
mpvPlayer = new mpv();and you're good to go.
You optionally pass a Json object with options to the constructor. Possible options, along with their default values are the following
{
"verbose": false,
"debug": false,
"socket": "/tmp/node-mpv.sock",
"audio_only": false
}verbosewill print various information on the consoledebugprints error messagessocketspecifies the socket mpv opensaudio_onlywill add the--no-videoand--no-audio-displayargument and start mpv in audio only mode
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"
]);This module provides a lot of different methods to interact with mpv, which can be called directly from the player object.
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)
Will load the
fileand start playing itloadStream (url)
Exactly the same as loadFile but loads a stream specified by
url, for example YouTube or SoundCloud.This function should be used to load YouTube and SoundCloud playlists, as loadPlaylist will not work.
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 ()
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
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 the information about the specified
property. The answers comes in form of an emitted getrequest event containing the specifiedid. This unfortunate, but to JavaScript's single threaded and event driven nature, it was the only way I foundaddProperty (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 roughly 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.
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();ToDo
- Fix the "Possible EventEmitter memory leak detected" bug
- Implement WebSocket support
Changelog
0.9.1
- Loop function implemented and property added to the default observed values
- MultiplyProperty added offer more free interaction with mpv
- Added a function to adjust the playback speed
0.9.0
- Playlist support added
0.8.2
- Added function to set the brightness, contrast, saturation, gamma and hue
- Added functions to zoom and rotate the video
0.8.1
- Major code reorganisation
- util is no longer required
- fullscreen() was renamed to toggleFullscreen()
- fullscreen() enters fullscreen mode, leaveFullscreen() leaves it
- unpause() renamed to resume()
- unpaused event renamed to resumed
- start event renamed to started
0.8.0
- Added support for various video related commands
- Subtitle support
0.7.4
- Custom command line arguments can now be provided to mpv
- As of this version lodash 4.0.0 or higher is required
- Minor fixes
0.7.3
- Added
audio_onlyoption - Videos are now officially supported, but the API is still missing
- Added
0.7.2
- Options object as paramter for the constructor
debugandverboseflags can be set- an arbitrary socket` can be specified
0.7.0
- Added events
0.6.0
- Allowed for free commands
- Free setProperty and getProperty methods
0.5.0
- Observing arbitrary properties
0.4.0
- Various control methods
0.3.0
- First API version
0.2.0
- Implemented communication interface via a local socket to talk to mpv