To have real-time communication with the backend in JavaScript, you can utilize sockets. The backend will then relay messages to other clients for actions like playing audio. For instance:
var http = require('http');
var fs = require('fs');
// Displaying index.html file to the client
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Setting up socket.io
var io = require('socket.io').listen(server);
// Console log when a client connects
io.sockets.on('connection', function (socket) {
console.log('A client is connected!');
socket.on('playAudio', function (someAudio) {
socket.broadcast.emit('playAudio');
});
});
server.listen(8080);
In the Frontend:
<template>
<div id="app" class="container-fluid">
<audio id="audio1">
<source src="../assets/mySong.wav" type="audio/wav">
</audio>
<button @click="playSound()" >Press for Sound</button>
</template>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!',
isPlaying: false
},
created: {
var socket = io.connect('http://localhost:8080');
socket.on('message', (message) => {
alert('The server has a message for you: ' + message);
})
socket.on('playAudio', () => {
if(!this.isPlaying){
this.playAudio();
}
})
},
methods: {
playAudio() {
socket.emit('playAudio');
var myMusic = document.getElementById("audio1");
this.isPlaying = true;
myMusic.play();
}
}
})
</script>
For more information: