0

I want to play and control audio file in electron-react app. Currently I am using Tone Js to do so. In my FilePlayer.ts I create the player by getting the bufferData of the file from the main process.

useEffect(() => {
    // Create and load the audio file when the component mounts
    const loadAudioFile = async () => {
      window.electron.ipcRenderer.on(GET_FILE_BUFFER, filePath);
      window.electron.ipcRenderer.on(GET_FILE_BUFFER, async (args) => {
        if (args === "error") {
          return;
        }
        let fileBuffer = args;
        const audioBuffer = await Tone.context.decodeAudioData(fileBuffer);
        const newPlayer = new Tone.Player(audioBuffer).toDestination();
        setPlayer(newPlayer);
      });
    };

    loadAudioFile();

    return () => {
      // Clean up resources when the component unmounts
      if (player) {
        player.stop();
        player.dispose();
      }
    };
  }, [filePath]);

The GET_FILE_BUFFER event calls the function below

import { IpcMainEvent } from "electron";
import fs from "fs";
import { GET_FILE_BUFFER } from "../../ipcEvents";
import path from "path";

const getFileBuffer = (event: IpcMainEvent, filePath: string) => {
  const resolvedPath = path.resolve(filePath);
  const doesExists = fs.existsSync(resolvedPath);

  if (doesExists) {
    const fileBuffer = fs.readFileSync(resolvedPath);
    event.reply(GET_FILE_BUFFER, fileBuffer);
  } else {
    event.reply(GET_FILE_BUFFER, "error");
  }
};

export default getFileBuffer;

And below is my index.ejs file as well

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      http-equiv="Content-Security-Policy"
      content="worker-src 'self' 'unsafe-inline';"
    />
    <meta
      http-equiv="Content-Security-Policy"
      content="worker-src 'self' blob:;"
    />
    <title>MYouSik</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

This is the error I am getting Refused to create a worker from 'blob:http://localhost:1212/1190dbff-156e-4f44-b740-205c2c7dd985' because it violates the following Content Security Policy directive: "worker-src 'self' 'unsafe-inline'".

If there is any other approach to playing audio, I'd love to hear that as well.

Silenx
  • 37
  • 6

0 Answers0