What is the best way to make a function of a "Node" file be called on my HTML5 site?

1

I'm doing a project of a simple music player using ElectronJS. For this I'm using a library that plays MP3 files (play-sound), how can I call this function inside my HTML? Do I need to create another file just for sound reproduction or can I play this function inside the main file?

CODE: index.js

console.log('Main process working');

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
const url = require('url');
const player = require('play-sound');

let win;

function createWindow(){
  win = new BrowserWindow({width: 300, height: 200, resizable: false, 
  minimizable: false, fullscreen: false, center: true});
  win.loadURL('file://${__dirname}/app/public/index.html');

  win.on('closed', () =>{
    win = null;
  });
}

app.on('ready', createWindow);

The code for playing sounds is:

var audio = player.play('nomedoarquivo.mp3', {/*efeitos*/}, (err) => {
    if (err) throw err
});

And to stop:

audio.kill();

How can I call this function inside my HTML file?

I accept suggestions from important libraries for all projects!

    
asked by anonymous 10.10.2018 / 02:04

1 answer

1

Unlike NW.js that shares the browser and node context in the same process which allows you to run packages npm

and access browser APIs in the same file .js , Electron does different, in Electron each context is executed in an isolated process, the way the node and the front-end code communicate is through messages. / p>

Messages :

Both the code in the main process and the rendering process use an instance of EventEmitter to exchange messages. in the main proceedings, the ipcMan module or the "webContents" property of "BrowserWindow" :

// use ipcMain no processo principal (sync/async) ----------------
const {ipcMain} = require('electron')
// ouvinte, resposta assíncrona
ipcMain.on('iniciar-player', (event, arg) => {
    // sua lógica aqui ...
    event.sender.send('player-reply', 'started-async')
})

// ouvinte, resposta síncrona
ipcMain.on('iniciar-player', (event, arg) => {
    // sua lógica aqui ...
    event.returnValue = 'started-sync'
})

// no processo de renderização (página web) ----------------------
const {ipcRenderer} = require('electron')

// ouvinte assíncrono (ouvinte antes do envio)
ipcRenderer.on('player-reply', (event, arg) => {
    console.log(arg) // "started-async"
})
// enviar
ipcRenderer.send('iniciar-player', 'argumento-ou-configuração')

// ouvinte síncrono
let response = ipcRenderer.sendSync('iniciar-player', 'argumento-ou-configuração')
console.log(response) // "started-sync"

In the main process run the logic of your module. The following example uses webContents in the main process (asynchronously):

// no processo principal (async) ---------------------------------
const {app, BrowserWindow} = require('electron')
let win = null

app.on('ready', () => {
    win = new BrowserWindow({width: 800, height: 600})
    win.loadURL('file://${__dirname}/app/public/index.html')
    // ouvinte
    win.webContents.on('iniciar-player', (/*parametros serializados em JSON por padrão*/) => {
        // sua lógica ...
        win.webContents.send('player-reply', 'started-async') // responda
    })
})

// no processo de renderização (página web) ----------------------
const {ipcRenderer} = require('electron')

// ouvinte assíncrono (ouvinte antes do envio)
ipcRenderer.on('player-reply', (event, arg) => {
    console.log(arg) // "started-async"
})
// enviar
ipcRenderer.send('iniciar-player', 'argumento-ou-configuração')

This is the basics about exchanging messages between the code executed on the render page and the main process.

  

Note: You can still abstract from these messages using the remote module if you just want to access the module without going through the main process

Remote :

You can access a specific module or file ( .js ) in the render process through the remote module:

// no processo de renderização (página web)
const player = require('electron').remote.require('play-sound')

// abrir player
const audio = player.play('nomedoarquivo.mp3', {/*efeitos*/}, (err) => {
    if (err) throw err
});

// simulando a iteração do usuário para encerrar o player
document.getElementById('btn-fechar-player').addEventListener('click', () => {
    audio.kill()
}, false)

Using remote seems much simpler, read the documentation ... "some things" are not recommended to do when using remote .

Fonts :

10.10.2018 / 06:54