简体   繁体   English

如何让我的音频在 socket.io 中播放?

[英]How do I get my audio to play in socket.io?

I am making a couple updates to my socket.io chat and I am trying to get audio every time a message is passed through.我正在对我的 socket.io 聊天进行一些更新,并且每次传递消息时我都试图获取音频。 When I send the message I get Uncaught (in promise) DOMException Here is the code that gets run when a message is passed through:当我发送消息时,我得到Uncaught (in promise) DOMException下面是当消息通过时运行的代码:

socket.on('new message', (data) => {
            var messageE = document.createElement('div')
            messageE.classList.add("well");
            messageE.classList.add("msg");
            messageE.innerHTML = '<strong>'+ data.user +'</strong>: ' + data.msg;
            console.log(messageE)

            chat.appendChild(messageE)
            audio.play()
          })

I may wont be able to respond till late afternoon.我可能要到下午晚些时候才能回复。

A few seconds ago i got the same error but i fixed it.几秒钟前我遇到了同样的错误,但我修复了它。 It is not the coolest solution but it works.这不是最酷的解决方案,但它有效。 What i did telling the browser itself to play the audio and not directly from a socket.我做了什么告诉浏览器本身播放音频而不是直接从套接字播放。

Make a outside Variable(example socketCheck) that is on false .false上创建一个外部变量(例如 socketCheck)。 That will become true when the socket is called.当套接字被调用时,这将成为现实 The if will continue when it is on true on false it wont. if将继续,当它为时为假,它不会。 When the sound got played turn the soundCheck on false again Here is a example;当播放声音时,再次将 soundCheck 设为false这是一个示例;

var soundCheck = false;

socket.on('new message', function(){
    soundCheck = true;
});

if (soundCheck) {
    sound.play();
    sound = false;
}

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

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