### Clone and Run Example Application Source: https://github.com/kagami/mpv.js/blob/master/README.md Clone the mpv.js repository, install dependencies, and run the example application. This command is primarily for Linux users who might need to set up system FFmpeg. ```bash git clone https://github.com/Kagami/mpv.js.git && cd mpv.js npm install # Only on Linux: npm run use-system-ffmpeg npm run example ``` -------------------------------- ### Install mpv.js with Prebuilt Binaries Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Use this command to install mpv.js. The install script automatically downloads the appropriate prebuilt binary for your platform. If the download fails, it falls back to `node-gyp rebuild`. ```bash npm install mpv.js ``` -------------------------------- ### Install mpv on Linux Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Use apt-get to install the mpv library and development files on Linux. This is a prerequisite for using mpv.js. ```bash apt-get install libmpv1 libavformat-dev ``` -------------------------------- ### Install mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/README.md Install the mpv.js package using npm. Ensure libmpv is installed on your system. ```bash npm install mpv.js --save ``` -------------------------------- ### Linux: Install Build Tools and Dependencies Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Install essential build tools and mpv development libraries on Linux. This includes build-essential, python, libmpv-dev, and libavformat-dev. ```shell apt-get install build-essential python ``` ```shell apt-get install libmpv-dev libavformat-dev ``` -------------------------------- ### ReactMPV Usage Example Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Demonstrates how to use the ReactMPV component in a React application. This example shows setting up event handlers for player readiness and property changes, and loading a video file. ```javascript const React = require("react"); const {ReactMPV} = require("mpv.js"); class Player extends React.PureComponent { constructor(props) { super(props); this.mpv = null; this.state = {pause: true, duration: 0}; } handleReady(mpv) { this.mpv = mpv; this.mpv.observe("pause"); this.mpv.observe("duration"); this.mpv.command("loadfile", "/path/to/video.mkv"); } handlePropertyChange(name, value) { this.setState({[name]: value}); } render() { return ( ); } } ``` -------------------------------- ### Electron Main Process Setup Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/README.md Set up the main process in Electron to integrate mpv.js. This involves configuring command-line switches and registering the plugin. ```javascript // Main process const {app, BrowserWindow} = require("electron"); const {getPluginEntry} = require("mpv.js"); const path = require("path"); const pluginDir = path.join(path.dirname(require.resolve("mpv.js")), "build", "Release"); if (process.platform !== "linux") process.chdir(pluginDir); app.commandLine.appendSwitch("no-sandbox"); app.commandLine.appendSwitch("ignore-gpu-blacklist"); app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); app.on("ready", () => { new BrowserWindow({webPreferences: {plugins: true}}).loadURL("file://" + __dirname + "/index.html"); }); ``` -------------------------------- ### Install mpv.js Runtime on Linux Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Installs the runtime library for mpv.js on Debian-based Linux systems. ```bash apt-get install libmpv1 ``` -------------------------------- ### Electron Renderer Process Setup Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/README.md Set up the renderer process in Electron using ReactMPV component. Handles player initialization and event handling. ```javascript // Renderer process const {ReactMPV} = require("mpv.js"); const React = require("react"); class Player extends React.PureComponent { handleReady(mpv) { mpv.observe("pause"); mpv.command("loadfile", "/path/to/video.mkv"); } handlePropertyChange(name, value) { this.setState({[name]: value}); } render() { return this.handleReady(m)} onPropertyChange={this.handlePropertyChange.bind(this)} />; } } ``` -------------------------------- ### Main Process Setup for mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/examples.md Sets up the main process in an Electron application to use mpv.js. Ensure the plugin directory is correctly resolved and appended as a pepper plugin. ```javascript // main.js const path = require("path"); const {app, BrowserWindow} = require("electron"); const {getPluginEntry} = require("mpv.js"); const pluginDir = path.join( path.dirname(require.resolve("mpv.js")), "build", "Release" ); if (process.platform !== "linux") { process.chdir(pluginDir); } app.commandLine.appendSwitch("no-sandbox"); app.commandLine.appendSwitch("ignore-gpu-blacklist"); app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); app.on("ready", () => { const win = new BrowserWindow({ width: 1280, height: 720, webPreferences: {plugins: true} }); win.loadURL(`file://${__dirname}/index.html`); }); app.on("window-all-closed", () => { app.quit(); }); ``` -------------------------------- ### Electron Main Process Setup for mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Configure the main process to load the mpv.js plugin. Ensure the plugin directory is correctly resolved and the necessary command-line switches are appended. ```javascript // Main process const {app, BrowserWindow} = require("electron"); const {getPluginEntry} = require("mpv.js"); const path = require("path"); const pluginDir = path.join(path.dirname(require.resolve("mpv.js")), "build", "Release"); if (process.platform !== "linux") process.chdir(pluginDir); app.commandLine.appendSwitch("no-sandbox"); app.commandLine.appendSwitch("ignore-gpu-blacklist"); app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); app.on("ready", () => { new BrowserWindow({webPreferences: {plugins: true}}); }); ``` -------------------------------- ### Install mpv on macOS Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Use Homebrew to install the mpv library on macOS. This is a prerequisite for using mpv.js. ```bash brew install mpv ``` -------------------------------- ### macOS: Install Xcode Command-Line Tools Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Install the Xcode command-line tools on macOS. This is a prerequisite for building native Node.js modules like mpv.js. ```shell xcode-select --install ``` -------------------------------- ### mpv.js Core Methods Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/README.md Examples of core mpv.js methods for controlling playback, properties, and events. ```javascript mpv.command("loadfile", "/path/to/video.mkv") ``` ```javascript mpv.property("pause", false) ``` ```javascript mpv.observe("time-pos") ``` ```javascript mpv.keypress(keyboardEvent) ``` ```javascript mpv.fullscreen() ``` ```javascript mpv.destroy() ``` ```javascript const embed = mpv.node() ``` -------------------------------- ### Install mpv.js Build Dependencies on Linux Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Installs development libraries required for building mpv.js on Debian-based Linux systems. ```bash apt-get install libmpv-dev libavformat-dev ``` -------------------------------- ### Build 32-bit Plugin on 64-bit Windows Source: https://github.com/kagami/mpv.js/blob/master/README.md Use this command to build the 32-bit version of the plugin on a 64-bit Windows system. This is useful for compatibility with 32-bit Node.js installations. ```bash node-gyp rebuild --arch=ia32 ``` -------------------------------- ### Package.json Dependencies Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Example of dependencies and peerDependencies typically found in a package.json file for an mpv.js project. ```json { "dependencies": { "prop-types": "^15.6.2", "prebuild-install": "^5.0.0" }, "peerDependencies": { "react": "^15.3.0 || ^16.0.0" } } ``` -------------------------------- ### Compile 64-bit NaCl Host Binaries on Windows Source: https://github.com/kagami/mpv.js/blob/master/README.md This command compiles 64-bit NaCl host binaries on Windows. Ensure Visual Studio 2013 is installed and configured correctly. ```bash make TOOLCHAIN=win PROJECTS="ppapi_cpp ppapi_gles2" ``` -------------------------------- ### Handle Platform Compatibility for Plugin Loading Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Account for platform differences when loading the mpv.js plugin. This example shows how to adjust the working directory based on the operating system to ensure the plugin can be found. ```javascript getPluginEntry() { // Platform detection in utility function const pluginDir = path.join( path.dirname(require.resolve("mpv.js")), "build", "Release" ); if (process.platform !== "linux") { process.chdir(pluginDir); } return getPluginEntry(pluginDir); } ``` -------------------------------- ### mpv.js Common Properties Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/README.md Examples of setting common mpv properties like pause, time-position, volume, and hardware decoding. ```javascript mpv.property("pause", false) — play ``` ```javascript mpv.property("time-pos", 30) — seek to 30s ``` ```javascript mpv.property("volume", 50) — set to 50% ``` ```javascript mpv.property("hwdec", "auto") — enable HW decoding ``` ```javascript mpv.property("fullscreen", true) ``` -------------------------------- ### Essential Properties Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Examples of essential properties that can be set on the mpv instance to control playback, seeking, volume, and hardware decoding. ```javascript // Play control mpv.property("pause", false); // Play mpv.property("pause", true); // Pause // Seeking mpv.property("time-pos", 30); // Seek to 30 seconds // Volume mpv.property("volume", 50); // Set to 50% // Hardware acceleration mpv.property("hwdec", "auto"); // Enable GPU decoding ``` -------------------------------- ### Get Plugin Entry String Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Generates the plugin entry string for Electron's register-pepper-plugins switch. Handles platform-specific path requirements and non-ASCII path restrictions. ```javascript function getPluginEntry(pluginDir: string, pluginName?: string): string ``` -------------------------------- ### ReactMPV Component Usage Source: https://github.com/kagami/mpv.js/blob/master/README.md Implement a React component using ReactMPV to embed and control an mpv player. This example demonstrates initializing the player, observing properties, and loading a video file. ```javascript const React = require("react"); const {ReactMPV} = require("mpv.js"); class Player extends React.PureComponent { constructor(props) { super(props); this.mpv = null; this.state = {pause: true, "time-pos": 0}; } handleMPVReady(mpv) { this.mpv = mpv; this.mpv.observe("pause"); this.mpv.observe("time-pos"); this.mpv.command("loadfile", "/path/to/video.mkv"); } handlePropertyChange(name, value) { this.setState({[name]: value}); } togglePause() { this.mpv.property("pause", !this.state.pause); } render() { return ( ); } } ``` -------------------------------- ### Log MPV Initialization and Load File Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Logs a message when MPV is initialized and then loads a specified file. Ensure MPV is ready before issuing commands. ```javascript // Log ready onReady={(mpv) => { console.log("MPV initialized"); mpv.command("loadfile", path); }} ``` -------------------------------- ### Implement onReady for Player Initialization Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Ensure the mpv instance is ready before sending commands by implementing the `onReady` callback. This is crucial for operations like loading files or observing properties. ```javascript class Player extends React.PureComponent { handleReady(mpv) { // SAFE: Plugin is ready mpv.command("loadfile", videoPath); mpv.observe("pause"); } render() { return this.handleReady(m)} />; } } ``` -------------------------------- ### ReactMPV.property Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Sets or gets a property of the mpv player. ```APIDOC ### property(name: string, value: any): void ```javascript mpv.property("pause", false); // Play mpv.property("volume", 50); // Set volume mpv.property("hwdec", "auto"); // Enable HW decoding ``` ``` -------------------------------- ### onReady Callback Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Callback fired when the mpv player finishes initializing and is ready to accept commands. This is the appropriate place to set initial properties, load files, and begin observing state changes. ```APIDOC ## onReady(mpv: ReactMPV): void ### Description Callback fired when the mpv player finishes initializing and is ready to accept commands. This is the appropriate place to set initial properties, load files, and begin observing state changes. ### Parameters #### Parameters - **mpv** (ReactMPV) - The ReactMPV component instance ### Usage Example ```javascript { // Safe to call mpv methods here mpv.observe("pause"); mpv.command("loadfile", "/path/to/video.mkv"); }} /> ``` ``` -------------------------------- ### Correct Plugin Path Handling on Linux Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Demonstrates the correct way to handle plugin directory changes on Linux, where `process.chdir` does not affect the forked renderer process. ```javascript // WRONG: Don't change CWD on Linux (won't affect renderer process) if (process.platform !== "linux") { process.chdir(pluginDir); } const pluginPath = getPluginEntry(pluginDir); // Result: "./mpvjs.node;application/x-mpvjs" ``` -------------------------------- ### Get PLUGIN_MIME_TYPE Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Retrieves the MIME type constant for the mpv.js plugin. This is used internally by the plugin embed element. ```javascript const PLUGIN_MIME_TYPE: string = "application/x-mpvjs" ``` -------------------------------- ### Initialize Player with onReady Callback Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Use the onReady callback to perform actions after the mpv player has initialized. This is the recommended place to set initial properties or load media. ```javascript { // Safe to call mpv methods here mpv.observe("pause"); mpv.command("loadfile", "/path/to/video.mkv"); }} /> ``` -------------------------------- ### Build Binaries for 32-bit and 64-bit Windows Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Use `node-gyp rebuild` with the `--arch=ia32` flag to build 32-bit binaries for Windows. Ensure consistency between Electron and mpvjs.node architectures. ```bash node-gyp rebuild # Default (64-bit) node-gyp rebuild --arch=ia32 # 32-bit ``` -------------------------------- ### Set/Get Common mpv.js Properties Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Use `mpv.property()` to get or set common player properties. Some properties are read-only and can only be observed. ```javascript mpv.property("pause", false) ``` ```javascript mpv.property("time-pos", 30) ``` ```javascript mpv.observe("duration") ``` ```javascript mpv.property("volume", 50) ``` ```javascript mpv.property("mute", true) ``` ```javascript mpv.property("fullscreen", true) ``` ```javascript mpv.property("hwdec", "auto") ``` ```javascript mpv.property("audio-delay", 0.5) ``` ```javascript mpv.property("sub-delay", 0.5) ``` ```javascript mpv.property("vid", 0) ``` ```javascript mpv.property("aid", 0) ``` ```javascript mpv.property("sid", 0) ``` ```javascript mpv.observe("eof-reached") ``` -------------------------------- ### Get Plugin DOM Node Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Retrieve the underlying HTML embed element for the mpv plugin. This is primarily for internal use. ```javascript const embedElement = mpv.node(); console.log(embedElement.tagName); // "EMBED" ``` -------------------------------- ### Build Plugin on x86 Source: https://github.com/kagami/mpv.js/blob/master/README.md This command rebuilds the native plugin using node-gyp. Ensure all prerequisites, including node-gyp and the NaCl SDK, are correctly set up. ```bash node-gyp rebuild ``` -------------------------------- ### Observe Media Duration Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Observe the 'duration' property to get the total playback duration in seconds. This property is read-only and only valid when media is loaded. ```javascript mpv.observe("duration"); // In callback: console.log(value) // e.g., 120.5 ``` -------------------------------- ### Get the Embed Node Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md The `node` method returns the underlying `` HTML element used by the ReactMPV component. This can be useful for direct DOM manipulation if necessary. ```javascript const embed = mpv.node(); ``` -------------------------------- ### Enable Hardware Acceleration Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Demonstrates how to enable hardware decoding for improved video playback performance. ```javascript mpv.property("hwdec", "auto"); ``` -------------------------------- ### Select Audio Track Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Choose the audio track to play. Use 0 for the first track and increment for subsequent tracks. ```javascript mpv.property("aid", 0); // Select first audio track mpv.property("aid", 1); // Select English track (if second) ``` -------------------------------- ### Load Video File with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Use the `command` method to load video files. Supports absolute paths and optional arguments like 'append'. ```javascript this.mpv.command("loadfile", "/absolute/path/to/video.mkv"); ``` ```javascript // or with options: this.mpv.command("loadfile", "/path/to/video.mp4", "append"); ``` -------------------------------- ### Volume Control with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Set the volume using the `volume` property and observe volume changes using `observe`. ```javascript // Set volume to percentage (0-100) this.mpv.property("volume", 50); ``` ```javascript // Get current volume by observing this.mpv.observe("volume"); // Then in onPropertyChange: console.log(value) when name === "volume" ``` -------------------------------- ### Log MPV Ready and Property Changes Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Add console logs to track when the MPV player is ready and to inspect property changes. Enable the DEBUG environment variable to log property changes. ```javascript handleReady(mpv) { console.log("MPV ready"); mpv.command("loadfile", videoPath); } handlePropertyChange(name, value) { if (process.env.DEBUG) { console.log(`Property: ${name} = ${value}`); } this.setState({[name]: value}); } ``` -------------------------------- ### Register Pepper Plugin with Electron Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Registers the mpv.js Pepper plugin with Electron using the getPluginEntry utility. This example shows platform-specific directory handling and command-line switch registration. ```javascript const path = require("path"); const {app} = require("electron"); const {getPluginEntry} = require("mpv.js"); const pluginDir = path.join(path.dirname(require.resolve("mpv.js")), "build", "Release"); // Platform-specific directory handling if (process.platform !== "linux") { process.chdir(pluginDir); } // Register the plugin with Electron app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); ``` -------------------------------- ### Get Plugin Entry Path Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md The `getPluginEntry` function generates the correct path and MIME type string for registering an mpv.js plugin in Electron. Provide the directory where your plugin is located. ```javascript const entry = getPluginEntry("/path/to/plugin"); // Returns: "./mpvjs.node;application/x-mpvjs" (or absolute path on Windows) ``` -------------------------------- ### Execute MPV Command Safely After Ready Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Ensures MPV commands are executed only after the MPV instance is fully initialized by using the onReady callback. Avoids errors from attempting to command an unready instance. ```javascript onReady={(mpv) => mpv.command(...)} ``` -------------------------------- ### Select Video Track Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Choose the video track to display. Use 0 for the first track and increment for subsequent tracks. ```javascript mpv.property("vid", 0); // Select first video track mpv.property("vid", 1); // Select second video track ``` -------------------------------- ### mpv.js Module Exports Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/configuration.md The mpv.js module exports three main items: a plugin MIME type constant, a function to get the plugin entry point, and a React component class. These are available for import via CommonJS. ```javascript module.exports = { PLUGIN_MIME_TYPE, // string: "application/x-mpvjs" getPluginEntry, // function: (pluginDir, pluginName?) => string ReactMPV // class: React.PureComponent }; ``` -------------------------------- ### Execute mpv Commands Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Use the `command` method to execute arbitrary mpv commands. Ensure the command and its arguments are correctly formatted. ```javascript mpv.command(cmd, ...args); ``` -------------------------------- ### Verify MPV Ready Callback Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Confirm that the `onReady` callback for the MPV component is being triggered. This is essential for ensuring the MPV instance is initialized before attempting to load files. ```javascript { console.log("MPV ready!"); mpv.command("loadfile", videoPath); }} /> ``` -------------------------------- ### ReactMPV.command Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Executes an mpv command with optional arguments. ```APIDOC ## ReactMPV Methods ### command(cmd: string, ...args: any[]): void ```javascript mpv.command("loadfile", "/path/to/video.mkv"); mpv.command("seek", 30, "absolute"); mpv.command("stop"); ``` ``` -------------------------------- ### Load a Video File Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Use `mpv.command("loadfile", ...)` to load a video file into the player. Provide the absolute path to the video. ```javascript mpv.command("loadfile", "/absolute/path/to/video.mkv"); ``` -------------------------------- ### Inspect dylib Dependencies on macOS Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Use the `otool -L` command to inspect the dynamic library dependencies of `libmpv.1.dylib` on macOS. This is useful when packaging your application. ```bash otool -L /usr/local/lib/libmpv.1.dylib ``` -------------------------------- ### Configure C++ ABI Compatibility for Builds Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Specifies the build flag `_GLIBCXX_USE_CXX11_ABI=0` in `binding.gyp` to ensure compatibility with systems using the old C++ ABI. ```json "defines": ["_GLIBCXX_USE_CXX11_ABI=0"] ``` -------------------------------- ### Compile ARM Host Binaries Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Compile ARM-specific host binaries for ppapi_cpp and ppapi_gles2. Ensure the NACL_SDK_ROOT environment variable is set correctly. This is necessary for building the plugin on ARM architectures. ```bash cd $NACL_SDK_ROOT/src make TOOLCHAIN=linux PROJECTS="ppapi_cpp ppapi_gles2" CFLAGS="-D_GLIBCXX_USE_CXX11_ABI=0" ``` ```bash cd /path/to/mpv.js node-gyp rebuild ``` -------------------------------- ### Configure BrowserWindow for Plugins Source: https://github.com/kagami/mpv.js/blob/master/README.md Enable the 'plugins' feature in the BrowserWindow constructor for Electron. This is necessary for the mpv.js plugin to function correctly. ```javascript const win = new BrowserWindow({ // ... webPreferences: {plugins: true}, // ... }); ``` -------------------------------- ### Enable Plugins in BrowserWindow Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Ensure that the `plugins` option is set to `true` within the `webPreferences` of your `BrowserWindow` constructor. This is a common requirement for plugins to load correctly. ```javascript // WRONG new BrowserWindow({width: 1280, height: 720}); // CORRECT new BrowserWindow({ width: 1280, height: 720, webPreferences: {plugins: true} // Required }); ``` -------------------------------- ### ReactMPV Constructor Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Initializes a new ReactMPV component instance. This constructor sets up the component's initial state and references. ```javascript constructor(props: ReactMPVProps) ``` -------------------------------- ### Screenshot Command Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Takes a screenshot of the current video frame and saves it to disk. ```APIDOC ## screenshot ### Description Take a screenshot and save it to disk. ### Method `command("screenshot")` ### Request Example ```javascript mpv.command("screenshot"); ``` ``` -------------------------------- ### Configure BrowserWindow for Plugin Support Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/configuration.md Enable plugin support in BrowserWindow instances by setting 'webPreferences.plugins' to true. This is a mandatory step for any BrowserWindow that will host the mpv.js player. ```javascript const win = new BrowserWindow({ width: 1280, height: 574, webPreferences: { plugins: true // REQUIRED for plugin support } }); ``` -------------------------------- ### ReactMPV.keypress Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Simulates a keypress event for the mpv player. ```APIDOC ### keypress(event: KeyboardEvent): void ```javascript document.addEventListener("keydown", (e) => mpv.keypress(e)); ``` ``` -------------------------------- ### Load mpv.js Plugin in Electron Main Process Source: https://github.com/kagami/mpv.js/blob/master/README.md Load the mpv.js plugin in the main process of an Electron application. Ensure the plugin directory is correctly resolved and command-line switches are appended for compatibility. ```javascript const path = require("path"); const {app} = require("electron"); const {getPluginEntry} = require("mpv.js"); // Absolute path to the plugin directory. const pluginDir = path.join(path.dirname(require.resolve("mpv.js")), "build", "Release"); // See pitfalls section for details. if (process.platform !== "linux") {process.chdir(pluginDir);} // Fix for latest Electron. app.commandLine.appendSwitch("no-sandbox"); // To support a broader number of systems. app.commandLine.appendSwitch("ignore-gpu-blacklist"); app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); ``` -------------------------------- ### Load File Command in mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Use `command("loadfile", path[, options])` to load a video file. The `options` parameter can be "replace" (default) or "append" to add to the playlist. ```javascript mpv.command("loadfile", "/path/to/video.mkv"); ``` ```javascript mpv.command("loadfile", "/path/to/video2.mkv", "append"); ``` -------------------------------- ### Register mpv.js Plugin with Electron Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/configuration.md Append the 'register-pepper-plugins' command-line switch to enable the mpv.js plugin before creating any BrowserWindows. This is required for plugin support. ```javascript const {getPluginEntry} = require("mpv.js"); app.commandLine.appendSwitch("no-sandbox"); app.commandLine.appendSwitch("ignore-gpu-blacklist"); app.commandLine.appendSwitch("register-pepper-plugins", getPluginEntry(pluginDir)); ``` -------------------------------- ### command(cmd, ...args) Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Sends a command to the mpv player with specified arguments. Arguments are converted to strings before transmission. ```APIDOC ## command(cmd, ...args) ### Description Sends a command to the mpv player. Arguments are converted to strings before transmission. ### Method command ### Parameters #### Path Parameters - **cmd** (string) - Required - The command name (e.g., "loadfile", "stop", "seek") - **args** (any[]) - Optional - Variadic arguments passed to the command ### Request Example ```javascript const mpv = /* ReactMPV instance */; // Load a video file mpv.command("loadfile", "/path/to/video.mkv"); // Seek to a specific time in seconds mpv.command("seek", 30, "absolute"); // Stop playback mpv.command("stop"); ``` ### Response #### Success Response - **undefined** (void) ``` -------------------------------- ### Check File Existence Before Loading Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Before attempting to load a file, verify its existence using `fs.existsSync()`. This prevents errors and provides a clearer message if the file is not found. ```javascript const fs = require("fs"); if (!fs.existsSync(videoPath)) { console.error("File not found:", videoPath); return; } mpv.command("loadfile", videoPath); ``` -------------------------------- ### Collect dylib Dependencies on macOS Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Execute the `scripts/collect-dylib-deps.sh` script to gather and bundle the necessary dylib dependencies for mpv on macOS. ```bash bash scripts/collect-dylib-deps.sh ``` -------------------------------- ### ReactMPV Instance Methods Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md These methods can be called on a ReactMPV instance to control the mpv player. ```javascript mpv.command(cmd, ...args); // Execute mpv command mpv.property(name, value); // Set mpv property mpv.observe(name); // Watch property for changes mpv.keypress(keyboardEvent); // Forward keyboard input mpv.fullscreen(); // Enter fullscreen mpv.destroy(); // Clean up resources ``` -------------------------------- ### Set and Observe Volume Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Set the playback volume to 50% and observe changes to the volume property. ```javascript mpv.observe("volume"); mpv.property("volume", 50); // Set to 50% ``` -------------------------------- ### Enable Hardware Decoding Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Use `mpv.property("hwdec", "auto")` to enable hardware-accelerated decoding, which can improve performance. ```javascript mpv.property("hwdec", "auto"); // Enable GPU decoding ``` -------------------------------- ### fullscreen() Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Requests fullscreen mode for the plugin embed element using the Fullscreen API. ```APIDOC ## fullscreen() ### Description Request fullscreen mode for the plugin embed element using the Fullscreen API. ### Method fullscreen ### Request Example ```javascript const mpv = /* ReactMPV instance */; // Enter fullscreen mpv.fullscreen(); // Exit fullscreen (handled via Escape key or document.webkitExitFullscreen()) ``` ### Response #### Success Response - **undefined** (void) ``` -------------------------------- ### Handle Keyboard Events Correctly Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Ensure that keyboard events are captured using `keydown` (or `keyup`) and that the event object itself is passed to `mpv.keypress()`. Passing only a key name is insufficient. ```javascript // CORRECT document.addEventListener("keydown", (e) => mpv.keypress(e)); ``` -------------------------------- ### Create React Player Component with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Implement a React component to integrate and control the mpv player. This includes handling player readiness, observing properties, and managing playback controls. ```javascript const React = require("react"); const ReactDOM = require("react-dom"); const {ReactMPV} = require("mpv.js"); class Player extends React.PureComponent { constructor(props) { super(props); this.mpv = null; this.state = { pause: true, "time-pos": 0, duration: 0 }; } handleMPVReady(mpv) { // Store reference to mpv instance this.mpv = mpv; // Observe properties we care about mpv.observe("pause"); mpv.observe("time-pos"); mpv.observe("duration"); // Load a video file mpv.command("loadfile", "/path/to/video.mkv"); } handlePropertyChange(name, value) { // Update React state when mpv properties change this.setState({[name]: value}); } handlePlayPause() { this.mpv.property("pause", !this.state.pause); } handleSeek(seconds) { this.mpv.property("time-pos", seconds); } render() { return (
this.handleMPVReady(mpv)} onPropertyChange={(name, value) => this.handlePropertyChange(name, value)} />
this.handleSeek(Number(e.target.value))} />
); } } ReactDOM.render(, document.getElementById("app")); ``` -------------------------------- ### Compile ARM Host Binaries Source: https://github.com/kagami/mpv.js/blob/master/README.md This command compiles ARM host binaries for the NaCl SDK. It requires specific CFLAGS to ensure ABI compatibility. ```bash make TOOLCHAIN=linux PROJECTS="ppapi_cpp ppapi_gles2" CFLAGS="-D_GLIBCXX_USE_CXX11_ABI=0" ``` -------------------------------- ### Forward Keyboard Input Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Use the `keypress` method to forward keyboard events to mpv. This allows for custom keybindings. ```javascript mpv.keypress(keyboardEvent); ``` -------------------------------- ### Debugging No Video Display with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Use this snippet to debug video display issues. It demonstrates how to observe playback time and load a test file after the mpv instance is ready. Ensure the file path is absolute and the file exists. ```javascript handleMPVReady(mpv) { mpv.observe("playback-time"); // Try a known working file first mpv.command("loadfile", "/absolute/path/to/test.mp4"); } handlePropertyChange(name, value) { console.log(`${name}: ${value}`); } ``` -------------------------------- ### Cross-Platform Path Handling for mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md This pattern correctly handles the working directory and plugin registration for mpv.js across different platforms. It adjusts the current working directory for non-Linux platforms to ensure the plugin is found. ```javascript const pluginDir = path.join( path.dirname(require.resolve("mpv.js")), "build", "Release" ); if (process.platform !== "linux") { process.chdir(pluginDir); } app.commandLine.appendSwitch( "register-pepper-plugins", getPluginEntry(pluginDir) ); ``` -------------------------------- ### Common Commands Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md This section outlines common commands available in mpv.js for controlling playback, managing subtitles, and taking screenshots. ```APIDOC ## Commands ### Playback Commands - **loadfile** - **Description**: Loads a video file. - **Usage**: `mpv.command("loadfile", path)` - **stop** - **Description**: Stops playback. - **Usage**: `mpv.command("stop")` - **seek** - **Description**: Seeks to a specific time or relative position. - **Usage (absolute)**: `mpv.command("seek", 30, "absolute")` - **Usage (relative)**: `mpv.command("seek", 5, "relative")` - **revert-seek** - **Description**: Undoes the last seek operation. - **Usage**: `mpv.command("revert-seek")` ### Subtitle Commands - **sub-add** - **Description**: Adds a subtitle file and optionally selects it. - **Usage**: `mpv.command("sub-add", path, "select")` - **sub-remove** - **Description**: Removes subtitles. - **Usage (all)**: `mpv.command("sub-remove")` - **Usage (specific track)**: `mpv.command("sub-remove", 0)` ### Screenshot Command - **screenshot** - **Description**: Saves a screenshot of the current frame. - **Usage**: `mpv.command("screenshot")` ``` -------------------------------- ### Platform Path Handling (Non-Linux) Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Use this snippet to change the current working directory to the plugin directory on platforms other than Linux. This ensures correct path resolution for plugins. ```javascript if (process.platform !== "linux") { process.chdir(pluginDir); } ``` -------------------------------- ### Load Absolute Video Path Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/troubleshooting-and-best-practices.md Ensure that the `videoPath` provided to the `mpv.command('loadfile', ...)` is an absolute path and that the file actually exists at that location. Use `path.resolve` for reliable path construction. ```javascript const path = require("path"); const videoPath = path.resolve("/absolute/path/to/video.mkv"); mpv.command("loadfile", videoPath); ``` -------------------------------- ### Send Commands to MPV Player Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Use the `command` method to send commands to the mpv player. Arguments are converted to strings. Useful for actions like loading files, seeking, or stopping playback. ```javascript const mpv = /* ReactMPV instance */; // Load a video file mpv.command("loadfile", "/path/to/video.mkv"); // Seek to a specific time in seconds mpv.command("seek", 30, "absolute"); // Stop playback mpv.command("stop"); ``` -------------------------------- ### loadfile Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Loads a video file into the player. It can either replace the current file or be appended to the playlist. ```APIDOC ## loadfile ### Description Loads a video file. The `options` parameter can be "replace" (default) or "append". ### Method command ### Parameters #### Path Parameters - **path** (string) - Required - The path to the video file. - **options** (string) - Optional - "replace" or "append". Defaults to "replace". ### Request Example ```javascript mpv.command("loadfile", "/path/to/video.mkv"); mpv.command("loadfile", "/path/to/video2.mkv", "append"); ``` ``` -------------------------------- ### Windows Plugin Path Handling Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md On Windows, `getPluginEntry()` returns absolute paths. Ensure you use the correct absolute path when registering plugins. ```javascript const pluginPath = getPluginEntry("C:\\path\\to\\plugin\\build\\Release"); // Result: "C:\\path\\to\\plugin\\build\\Release\\mpvjs.node;application/x-mpvjs" ``` -------------------------------- ### Import mpv.js Modules Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Import necessary components from the mpv.js library. This is typically the first step in using the library. ```javascript const {PLUGIN_MIME_TYPE, getPluginEntry, ReactMPV} = require("mpv.js"); ``` -------------------------------- ### Fullscreen Control with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Toggle fullscreen mode using the `fullscreen` method and `webkitExitFullscreen`. ```javascript // Enter fullscreen this.mpv.fullscreen(); ``` ```javascript // Exit fullscreen document.webkitExitFullscreen(); ``` -------------------------------- ### Forward Keyboard Events with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Forward keyboard events to mpv for handling by the player. Filter events as needed. ```javascript // Forward keyboard events to mpv document.addEventListener("keydown", (event) => { // Filter if needed (e.g., skip when user is typing) this.mpv.keypress(event); }); ``` -------------------------------- ### Keypress Command Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Sends a key press event to MPV's input system. ```APIDOC ## keypress ### Description Send a key press to mpv's input system. This is what the `keypress()` method uses internally. ### Method `command("keypress", key)` ### Parameters #### Path Parameters - **key** (string) - Required - The key to press (e.g., "UP", "Shift+LEFT", "Ctrl+q"). ### Request Example ```javascript mpv.command("keypress", "UP"); mpv.command("keypress", "Shift+LEFT"); mpv.command("keypress", "Ctrl+q"); ``` ``` -------------------------------- ### keypress(event) Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/api-reference.md Sends a keyboard event through mpv's input handler, triggering configured keybindings. ```APIDOC ## keypress(event) ### Description Send a keyboard event through mpv's input handler, triggering configured keybindings. Automatically converts JavaScript key names to mpv key syntax and filters out modifier-only keys. ### Method keypress ### Parameters #### Path Parameters - **event** (KeyboardEvent) - Required - DOM KeyboardEvent object with `key`, `shiftKey`, `ctrlKey`, and `altKey` properties ### Request Example ```javascript const mpv = /* ReactMPV instance */; // Attach to document keyboard listener document.addEventListener("keydown", (e) => { mpv.keypress(e); }); // Or in a React event handler
mpv.keypress(e)} /> ``` ### Response #### Success Response - **undefined** (void) ``` -------------------------------- ### Set Volume Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Use `mpv.property("volume", ...)` to set the player's volume. The value is a percentage from 0 to 100. ```javascript mpv.property("volume", 50); // Set to 50% ``` -------------------------------- ### Configure Hardware Decoding Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Enable or disable hardware decoding. 'auto' attempts to use hardware decoding if available, while 'no' disables it. ```javascript mpv.property("hwdec", "auto"); // Enable hardware decoding mpv.property("hwdec", "no"); // Disable hardware decoding ``` -------------------------------- ### Set Property: aid/sid Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Switches the audio or subtitle track based on the provided index. ```APIDOC ## Set Audio/Subtitle Track Property ### Description Sets the audio track ('aid') or subtitle track ('sid') to a specific language index. ### Method `property(propertyName, languageIndex)` ### Parameters #### Path Parameters - **propertyName** (string) - Required - The property to set ('aid' or 'sid'). - **languageIndex** (number) - Required - The index of the desired audio or subtitle track. ### Request Example ```javascript // Switch audio track this.mpv.property("aid", languageIndex); // Optionally switch corresponding subtitle this.mpv.property("sid", languageIndex); ``` ``` -------------------------------- ### Avoid Changing Working Directory on Windows Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/platform-specific-notes.md Do not use `process.chdir()` on Windows as it can lead to issues with path resolution. This is only applicable to macOS and Linux. ```javascript // WRONG on Windows if (process.platform !== "linux") { process.chdir(pluginDir); } // RIGHT: Only on macOS/Linux if (process.platform !== "linux") { process.chdir(pluginDir); } ``` -------------------------------- ### Enter Fullscreen Mode Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/00-START-HERE.md Call the `fullscreen` method to make the mpv player enter fullscreen mode. ```javascript mpv.fullscreen(); ``` -------------------------------- ### Switch Audio and Subtitle Tracks Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/properties-and-commands.md Allows switching between different audio and subtitle tracks by setting their respective properties. Assumes track indices correspond. ```javascript handleMPVReady(mpv) { mpv.observe("aid"); // Audio track mpv.observe("sid"); // Subtitle track } switchLanguage(languageIndex) { // Switch audio track this.mpv.property("aid", languageIndex); // Optionally switch corresponding subtitle this.mpv.property("sid", languageIndex); } ``` -------------------------------- ### Use Absolute Paths for Files Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/quick-reference.md Always resolve user-provided paths to absolute paths using path.resolve before passing them to mpv.command('loadfile'). This ensures consistent behavior regardless of the current working directory. ```javascript const path = require("path"); const videoPath = path.resolve(userPath); // Absolute path mpv.command("loadfile", videoPath); ``` -------------------------------- ### Hardware Acceleration with mpv.js Source: https://github.com/kagami/mpv.js/blob/master/_autodocs/guide-getting-started.md Enable or disable hardware decoding using the `hwdec` property. ```javascript // Enable hardware decoding this.mpv.property("hwdec", "auto"); ``` ```javascript // Disable hardware decoding this.mpv.property("hwdec", "no"); ```