Is there a feature that allows a user to trigger an audio playback on my web application by clicking a button, and enable other users to listen to the same sound as well?

I'm currently using Vue to develop a web application. At the moment, I have implemented a button in my code that plays a sound when clicked, and it is functioning properly.

<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>
playSound() {
var myMusic = document.getElementById("audio1");
myMusic.play();
</script>

However, there is a limitation where only the user initiating the sound can hear it. Is there a way to make this feature accessible to multiple users simultaneously, so that if one user triggers the sound, all others on the same webpage can also hear it?

Answer №1

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:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for managing cookies in an Angular.js project

At the moment, I am utilizing an AngularJS application. To store certain values in a cookie, I incorporated the angular-cookies-min script to add values to cookies. The following code snippet was used to save values to a cookie: $cookieStore.put("userIn ...

Having trouble retrieving the DD-MM-YYYY date format in Vue.js from MySQL database

Hi, I am struggling with setting the format of dateCreated (the date when the account was created) to DD-MM-YYYY. In my Vue page, the code looks like this: https://i.sstatic.net/8SSAE.png The issue is that the website displays the date in the format sho ...

The occurrence of an error event in events.js at line 160 has not been properly handled and has resulted in an exception being

I recently encountered an issue with a project I was working on that was built using gulp. After updating the node version to v6.3.1, a task named 'html' started throwing an error. Here is a snippet of the error code: bogon:toClient work$ gulp ...

Refreshing CKFinder Form Field with jQuery

Looking to update the value of an input field .ckfinder-input using CKFinder's pop-up image selector. Everything runs smoothly until attempting to assign the selected image URL to the input field with input.val() = fileUrl, resulting in the error mess ...

Is there a simple method to transform a JavaScript object into pairs formatted as "name": "Fred", "value": "Blue"?

I'm trying to find a solution for converting an object into a specific string format using JavaScript. Here is the object in question: Object name: Fred lastname: Jones city: Los Angeles The desired output should look like this: // Do want this [ ...

Generating small image previews in JavaScript without distorting proportions

I am currently working on a client-side Drag and Drop file upload script as a bookmarklet. To prepare for the upload process, I am utilizing the File API to convert the images into base64 format and showcase them as thumbnails. These are examples of how m ...

It seems like there may be an issue with the React Table Pagination in reactjs

As a newcomer to React JS, I have been utilizing react-table to create a component that can filter, sort, and paginate sample data from a JSON file. If you are interested in the tutorial I am following, you can find it here: Currently, I am encountering ...

Update the reference value within a nested component

I am looking to update the value of the ref in the parent component from the child component. I have attempted using emits and passing the ref to the child component to make changes, but so far I have had no success. When trying to access the ref in the ch ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

Trouble with serving CSS files using Express static directory

In my app.js file, I have the following code: app.use(express.static(path.join(__dirname, '../public'))); This code snippet is from my main layout page: <link rel="stylesheet" href="/css/styles.css"> Despite trying various combinations, ...

Angular struggles to display carousels using templates

I've been working with Angular and UI Bootstrap components to create a carousel using the templateUrl argument for slide rendering. However, I've encountered some issues along the way. Firstly, nothing seems to appear on the page when I run it, a ...

Having Difficulty Modifying the CSS Styles of a Specific Class

I've been struggling with a CSS styling issue for some time now. The problem lies in targeting the class for the thumbnail preview of vue2-dropzone (which shares similar properties with dropzone.js based on documentation). Each time I upload an image, ...

Exploring the dynamic duo of HTML and JQuery within the Webstorm IDE

I'm facing a simple issue with my webstorm project. It consists of an HTML file, CSS file, and JS file. In my project, I tried creating a circle using a "div" element and attempted to make it fade out upon clicking with JavaScript. However, the funct ...

JavaScript functions do not work within the HTML code

I am currently working on my debut website and I'm facing an issue with the JavaScript file not functioning properly. Is there a chance you can help me troubleshoot this? I'm still in the learning stages of programming. This is the HTML content ...

Send information and showcase it on the following screen using ReactJS

Having recently started using ReactJS for a front-end development project, I encountered a challenge that I need help with. I want to prompt the user for their name using an input field after a question like "What is your name?". Once the user inputs their ...

The for loop does not pause until the ajax response is received

When I enter the for loop, an ajax call is made. However, the for loop does not wait for the ajax call to receive a response before incrementing the value, causing the response to update to the wrong div element. For example: Let's say we have ' ...

jQuery UI - Inconsistent results with multiple autocomplete feature

I am facing an issue with the tags.json file provided below: [ {"label" : "Aragorn"}, {"label" : "Arwen"}, {"label" : "Bilbo Baggins"}, {"label" : "Boromir"} ] In addition, I have a JavaScript code snippet (which ...

Prevent users from submitting the form again within the last 7 minutes after they have already clicked the Submit button

I am looking to implement a feature where the 'Submit' button is disabled for 7 minutes. During this time, I want a message displayed next to the form that says: "Wait 7 minutes before submitting". Once the countdown is complete, I would like the ...

Expanding the Functionality of Vue Using Class-Based Components and Mixins

Hey there, I'm looking to convert this component into a TypeScript-based class component. Any tips on how to do that? <script> import { Line } from 'vue-chartjs' import { chartLast30Days, chartStylingMethods } from '#/mixins&apos ...