{
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 (
);
}
}
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");
```