Created
July 1, 2021 06:27
-
-
Save mustofa-id/feec15eea99d83eb7be7a1d9c7246413 to your computer and use it in GitHub Desktop.
Nodejs play audio file using available player
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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