繁体   English   中英

有没有办法让用户点击在我的 web 应用程序中播放音频的按钮并让另一个用户也听到那个声音?

[英]Is there a way for a user to click on a button that plays audio in my webapp and have another user hear that sound too?

我正在使用 Vue 创建一个 web 应用程序。 现在我有这个代码,它有一个按钮,当我按下它时,它会播放声音并且可以工作。

<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>

但它仅适用于访问该页面的当前用户。 如果我有另一个用户也在查看该网页,他们将听不到它。 如果我有 2 个用户在他们自己的浏览器中查看同一页面,并且其中一个用户按下按钮,另一个人可以听到它,我需要做什么?

您需要在 javascript 中使用套接字与后端进行实时通信,后端也会将该消息发送给其他客户端以播放音频。 例如:

var http = require('http');
var fs = require('fs');

// Loading the index file . html displayed 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);
    });
});

// Loading socket.io
var io = require('socket.io').listen(server);

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
    console.log('A client is connected!');
    socket.on('playAudio', function (someAudio) {
        socket.broadcast.emit('playAudio');
    }); 
});


server.listen(8080);

在前端:

<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>

更多信息: https: //openclassrooms.com/en/courses/2504541-ultra-fast-applications-using-node-js/2505653-socket-io-let-s-go-to-real-time https:// /itnext.io/building-a-node-js-websocket-chat-app-with-socket-io-and-react-473a0686d1e1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM