Introduction to Node Media Server
Node Media Server is a powerful streaming server implementation that leverages the capabilities of Node.js to provide lightweight and efficient media streaming functionalities. It supports several key streaming protocols, such as RTMP, HLS, and DASH, making it ideal for building high-performance streaming applications.
Getting Started with Node Media Server
To start using Node Media Server, you need to install it via npm:
npm install node-media-server
Basic Configuration
Below is a basic configuration example for setting up Node Media Server:
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
allow_origin: '*'
}
};
const nms = new NodeMediaServer(config); nms.run();
API Examples
Node Media Server comes with a versatile API to handle various streaming functions.
API: onStart
This event is triggered when the server starts:
nms.on('postPublish', (id, StreamPath, args) => {
console.log(`[NodeEvent on postPublish] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
API: onStop
This event is triggered when the server stops:
nms.on('donePublish', (id, StreamPath, args) => {
console.log(`[NodeEvent on donePublish] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
API: onPlay
This event is triggered when a stream starts playing:
nms.on('postPlay', (id, StreamPath, args) => {
console.log(`[NodeEvent on postPlay] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
Example Application: Live Streaming with Node Media Server
Below is an example of how to set up a live streaming application using Node Media Server:
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
allow_origin: '*'
}
};
const nms = new NodeMediaServer(config);
nms.on('postPublish', (id, StreamPath, args) => {
console.log(`[NodeEvent on postPublish] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.on('donePublish', (id, StreamPath, args) => {
console.log(`[NodeEvent on donePublish] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.on('postPlay', (id, StreamPath, args) => {
console.log(`[NodeEvent on postPlay] id=${id} StreamPath=${StreamPath} args=${JSON.stringify(args)}`);
});
nms.run();
With this configuration, you can easily set up a robust live streaming service using Node Media Server.
Hash: 6f232897a6044e7fcfce0d0b9232e5cdbfddd755d80f13f1df75c2fccea5c8b0