electron.js – niech gra muzyka

Poniżej znajduje się program, który odtwarza plik mp3, po wybraniu z dysku

plik index.html

<!DOCTYPE html>
<html>
<head>
  <title>MP3 Player</title>
</head>
<body>
  <input type="file" id="mp3File" accept=".mp3">
  <button id="playButton">Play</button>
  <button id="pauseButton">Pause</button>
  <script src="renderer.js"></script>
</body>
</html>

plik main.js

const { app, BrowserWindow } = require('electron');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });

  win.loadFile('index.html');
}

app.whenReady().then(() => {
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

plik renderer.js

const { ipcRenderer } = require('electron');

const playButton = document.getElementById('playButton');
const pauseButton = document.getElementById('pauseButton');
const mp3FileInput = document.getElementById('mp3File');

let audioPlayer = new Audio();

playButton.addEventListener('click', () => {
  if (audioPlayer.src) {
    audioPlayer.play();
  }
});

pauseButton.addEventListener('click', () => {
  audioPlayer.pause();
});

mp3FileInput.addEventListener('change', (event) => {
  const selectedFile = event.target.files[0];
  
  if (selectedFile) {
    const filePath = URL.createObjectURL(selectedFile);
    audioPlayer.src = filePath;
    audioPlayer.load();
  }
});