Nodejs player 基于命令行的播放器
Nodejs player 基于命令行的播放器
github: https://github.com/turingou/player
妈蛋的,想做豆瓣fm的cli工具,找了好久没找到一个像样的包装,其实就几行代码,刚写了一个,不知道有没有人用的到~
直接安装:npm install player
Nodejs Player: 基于命令行的播放器
GitHub:
背景介绍:
最近想要做一个类似豆瓣FM的命令行播放器(CLI工具),却发现市面上并没有找到一个令人满意的解决方案。其实实现起来并不复杂,所以我决定自己动手写一个。虽然只有几行代码,但希望能帮到有需要的人。
安装方法:
你可以通过npm直接安装这个工具:
npm install player
示例代码:
以下是一个简单的Node.js命令行播放器示例,使用了play-sound
库来处理音频播放功能。
首先,你需要安装必要的依赖:
npm install play-sound
接下来,创建一个名为 player.js
的文件,并添加以下代码:
const player = require('play-sound')(opts = {})
const fs = require('fs')
// 播放指定路径的音频文件
function playAudio(filePath) {
if (fs.existsSync(filePath)) {
player.play(filePath, function(err) {
if (err) throw err;
console.log("Playing audio...")
});
} else {
console.error(`File not found at ${filePath}`);
}
}
// 从命令行参数中获取音频文件路径
const args = process.argv.slice(2);
if (args.length > 0) {
const filePath = args[0];
playAudio(filePath);
} else {
console.log("Please provide the path to an audio file as a command line argument.");
}
使用说明:
- 确保你已经安装了
player
包。 - 将上述代码保存为
player.js
文件。 - 运行命令行,例如:
node player.js /path/to/your/audiofile.mp3
- 如果一切正常,程序将播放指定路径的音频文件。
总结:
这个简单的Node.js CLI播放器可以作为一个基础模板,你可以在此基础上增加更多的功能,如支持更多音频格式、提供播放列表、增加暂停和停止功能等。希望这个小工具对你有所帮助!
通过上述代码,我们可以看到如何使用Node.js来创建一个简单的命令行音频播放器。这不仅展示了Node.js的强大功能,还提供了一个实用的CLI工具的示例。
对于 “Nodejs player 基于命令行的播放器” 这个帖子,以下是一个简单的示例,展示如何创建一个基于命令行的音频播放器。这个示例将使用 Node.js 的 child_process
模块来调用系统音频播放器。
示例代码
const { exec } = require('child_process');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function playAudio(file) {
// 使用系统默认的音频播放器打开音频文件
exec(`open ${file}`, (error, stdout, stderr) => {
if (error) {
console.error(`执行出错: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
function start() {
rl.question('请输入音频文件路径: ', (file) => {
playAudio(file);
rl.close();
});
}
start();
说明
- 引入模块:首先,我们引入了
child_process
模块中的exec
方法,用于执行外部命令;以及readline
模块用于处理命令行输入。 - 读取命令行输入:通过
readline.createInterface()
创建一个 readline 接口实例,用于接收用户输入的音频文件路径。 - 播放音频:定义
playAudio
函数,该函数接受一个文件路径参数,并通过exec
执行系统命令(例如open
)来播放音频文件。这里的open
命令是 macOS 系统的默认命令,用于打开文件或应用程序。 - 启动播放器:定义
start
函数,提示用户输入音频文件路径,并调用playAudio
函数进行播放。
这个简单的命令行播放器可以作为一个起点,你可以根据需要添加更多功能,如支持不同平台、增加播放控制(暂停、停止等)、列表播放等功能。