Skip to content

Instantly share code, notes, and snippets.

@mustofa-id
Created July 1, 2021 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustofa-id/feec15eea99d83eb7be7a1d9c7246413 to your computer and use it in GitHub Desktop.
Save mustofa-id/feec15eea99d83eb7be7a1d9c7246413 to your computer and use it in GitHub Desktop.
Nodejs play audio file using available player
import { spawn } from "child_process";
import { readdirSync } from "fs";
import path from "path";
class AudioPlayer {
constructor({ player, folder, ext = "wav" }) {
if (!player || !folder) throw new Error(`Parameters 'player' and 'folder' are required`)
this.player = player;
this.folder = path.resolve(folder);
this.ext = `.${ext}`;
}
play = (fileName) => new Promise((resolve, reject) => {
if (!fileName) return reject(new Error("Parameter file name is required"))
const fileWithExt = fileName.endsWith(this.ext) ? fileName : `${fileName}${this.ext}`
const filePath = path.join(this.folder, fileWithExt);
const proc = spawn(this.player, [filePath], { stdio: "ignore" });
proc.on('error', reject)
proc.on("close", (code) => {
if (code !== 0) {
const message = `Unable to play audio file: ${code}`
return reject(new Error(message))
}
resolve()
});
})
}
let playedAt = 0;
const player = new AudioPlayer({ player: 'aplay', folder: './audios' });
const files = readdirSync(player.folder);
(async function test() {
try {
if (playedAt === files.length) return console.log("Done");
console.log("Playing: ", files[playedAt]);
await player.play(files[playedAt]);
++playedAt;
test();
} catch (error) {
console.error({ error })
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment