I want to play audio files (mp3/wav) in my electron app, Right now I am using react as ui and sending ipcEvents back and forth between main process and renderer to try to play the audio file. I am using Tone js for doing so, below is the code where I've registered events for managing audio files.
import path from "path";
import fs from "fs";
import * as Tone from "tone";
import { IpcMain, IpcMainEvent } from "electron";
import { LOAD_LITE_AUDIO, PAUSE_LITE_AUDIO, PLAY_LITE_AUDIO, LITE_AUDIO_STATUS } from "../../../../ipcEvents";
let player: Tone.Player | null;
const registerLiteAudioEvents = (ipcMain: IpcMain) => {
ipcMain.on(LOAD_LITE_AUDIO, (event: IpcMainEvent, filePath) => {
if (player) {
player.stop();
player.dispose();
player = null;
}
const loadAudioFile = async () => {
const audioFilePath = path.resolve(filePath);
const fileExists = fs.existsSync(audioFilePath);
if (fileExists) {
const fileBuffer = fs.readFileSync(audioFilePath);
const audioBuffer = await Tone.context.decodeAudioData(fileBuffer);
player = new Tone.Player(audioBuffer).toDestination();
// Start playing the audio
event.reply(PLAY_LITE_AUDIO);
} else {
console.error("Audio file does not exist:", audioFilePath);
}
};
(async () => {
await loadAudioFile();
})(); // IIFE
});
ipcMain.on(PLAY_LITE_AUDIO, (event: IpcMainEvent) => {
if (player) {
player.start();
event.reply(LITE_AUDIO_STATUS, { isPlaying: true, initialVolume: 100 });
}
});
ipcMain.on(PAUSE_LITE_AUDIO, (event: IpcMainEvent) => {
if (player) {
player.stop();
event.reply(LITE_AUDIO_STATUS, { isPlaying: false, initialVolume: 100 });
}
});
};
export default registerLiteAudioEvents;
I've checked the imports and event firing already, events are being fired properly all imports are correct other than the import Tone from "tone"
I'm not really sure about this one,
Below is the error I am getting
[8484:0629/162814.849:ERROR:CONSOLE(2)] "TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))", source: node:electron/js2c/sandbox_bundle (2)
(node:8484) UnhandledPromiseRejectionWarning: ReferenceError: AudioBuffer is not defined
...at More lines // they didn't tell the problem so i removed em
(node:8484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting
a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
I'd like to know how can I make this work, over that I'm also down to know any other approach to play audio files with electron.