7

im developing an electron app, which needs to play a sound in case of incoming message from webSocket connection. The websocket is handled on the main process, as the user switches pages during usage. I can not play the sound from the renderer, as i don't know in which page the user is at the moment, the webSocket message comes in (in worst case he is in between to pages while navigating).

Is there chance to play back audio on main process? The audio file is stored locally within the project file structure.

Kind regards,

BoxSon

MadMaxAPP
  • 1,035
  • 2
  • 16
  • 39

2 Answers2

5

I found this simple npm package for playing sounds without renderer, and you can easily include it to your electron project.

Firstly, you need to install by npm install sound-play or save directly to your project with npm install sound-play --save and

initialize by this

const sound = require("sound-play");

and to play file just one line of code

sound.play("file.mp3");

You can learn more on the official site through this link

Mussa Charles
  • 659
  • 7
  • 10
3

Found a workaround to solve this by my own:

  • create and open a hidden window.
  • In this window load a HTML5 audio player
  • via IPC send message to this hidden window from main to play a sound.

Little bit of effort but works like a charm.

Don't forget to destroy the hidden window on application closure (application won't close if you forget this step).

MadMaxAPP
  • 1,035
  • 2
  • 16
  • 39
  • Any chance you could provide could for this? I'm learning Electron's API and have the same problem right now. – Dawid Laszuk Apr 19 '20 at 22:26
  • Is this a safe work around or would it be considered a hack? I'm facing a similar problem – Matt Jun 10 '20 at 22:20
  • 1
    This is a safe workaround. We don’t use something in a way it was not supposed to be used for i would say. – MadMaxAPP Jun 17 '20 at 11:54
  • This should be the accepted answer. "sound-play" library does not even has stop/pause capabilities. In my case the app needed to play a sound, in loop, from a user folder and doing something like `const sound = new Audio(path_to_filesystem)` did not worked. Instead i had to convert the audio to base64 and then pass to Audio constructor. `const sound = new Audio(base64_audio); sound.play();` To loop: `sound.loop = true;` And to stop: `sound.pause()` – italo.portinho Jun 05 '22 at 01:46