音频播放器返回Uncaught (In promise): (DOMException) 该元素没有受支持的来源。

huangapple go评论82阅读模式
英文:

Audio player returns Uncaught (In promise): (DOMException) The element has no supported sources

问题

以下是您要翻译的内容:

在我的音频播放器(ka-musicplayer.glitch.me)中,我发现一个缺陷,就是当我通过键入MP3文件的路径来播放音频时,它会返回那个路径。如果我预定义MP3文件,它就能正常工作。您可以在这里查看代码这里

var input = document.getElementById("input");
var inputVal = "";
if (input) {
  inputVal = input.value;
}

var player = new Audio(inputVal);
player.crossOrigin = "anonymous";
var s2 = document.createElement("button");
s2.innerText = "播放";
s2.addEventListener("click", function() {
  player.src = inputVal;
  player.play();
});
document.body.appendChild(s2);
<!DOCTYPE html>
<head></head>
<body>

<input id="input" />
请查看当前浏览器的JavaScript控制台以查看错误

请注意,以上是您提供的代码的翻译部分,不包含其他内容。

英文:

So in my audio player (ka-musicplayer.glitch.me) i saw a flaw that when i played audio by typing the path to an MP3 it returned that. If i predefine the MP3s, it works. Feel free to see the code here.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

   var input = document.getElementById(&quot;input&quot;);
      var inputVal = &quot;&quot;;
      if (input) {
        inputVal = input.value;
      }

      var player = new Audio(inputVal);
      player.crossOrigin = &quot;anonymous&quot;;
  var s2 = document.createElement(&quot;button&quot;);
      s2.innerText = &quot;Play&quot;;
      s2.addEventListener(&quot;click&quot;, function() {
        player.src = inputVal;
        player.play();
      });
      document.body.appendChild(s2);

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;


&lt;input id=&quot;input&quot; /&gt;
Check JS Console in current browser for error

<!-- end snippet -->

答案1

得分: 0

调查了Audio()构造函数后,我已经修改了您的代码。

首先,您可以在HTML中编写button元素,并添加事件侦听器,而不是动态生成它。

<!DOCTYPE html>
<head></head>
<html>
<body>
    <input id="input" type="text">
    <button id="play">播放</button>
</body>
</html>

此外,至少在您提供的代码片段中,您立即获取了输入的值。我建议在单击播放按钮时获取该值:

const input = document.getElementById("input");
const playButton = document.getElementById("play");

playButton.addEventListener("click", function() {
    if (input.value.length) {
        let inputVal = input.value;
        var player = new Audio(inputVal);
        player.crossOrigin = "anonymous";
        player.addEventListener("canplaythrough", function() {
            player.play();
        })
    }
})

请注意播放器上的"canplaythrough"侦听器,这会延迟播放音频,直到音频元素和文件本身完全加载完成。您也不需要为元素分配src,传递到Audio()构造函数的URL会自动分配给源。

英文:

After investigating the Audio() constructor, I've revised your code.

Firstly, you could write the button element in your HTML and add an event listener rather than generating it dynamically.

&lt;!DOCTYPE html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;html&gt;
&lt;body&gt;
    &lt;input id=&quot;input&quot; type=&quot;text&quot;&gt;
    &lt;button id=&quot;play&quot;&gt;Play&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

Also, at least in the snippet you provided, you're grabbing the value of the input right away. I'd grab the value when you click the play button:

const input = document.getElementById(&quot;input&quot;);
const playButton = document.getElementById(&quot;play&quot;);


playButton.addEventListener(&quot;click&quot;, function() {
    if (input.value.length) {
        let inputVal = input.value;
        var player = new Audio(inputVal);
        player.crossOrigin = &quot;anonymous&quot;;
        player.addEventListener(&quot;canplaythrough&quot;, function() {
            player.play();
        })
    }
})

Notice the &quot;canplaythrough&quot; listener on the player--this delays playing the audio until the audio element and file itself have been completely loaded. You also didn't need to assign a src to the element; the URL passed into the Audio() constructor is automatically assigned to the source.

答案2

得分: 0

我也在动态添加的歌曲以"未捕获的(在承诺中):(DOM异常)元素没有受支持的源"结束时遇到了问题。在页面刷新时最初加载的歌曲运行得很好,但新添加的歌曲甚至尽管代码相同,也无法正常播放。我尝试使用"song.srcObj = null;"来丢弃旧歌曲,以帮助垃圾收集器,然后我尝试始终生成唯一的歌曲网址,如果加载相同的歌曲时出现问题(element.song = new Audio("https://domain.cz" + element.file + "?" + new Date().getTime());)

真正有帮助的是:

song.load();

更准确地说,由于播放是一个承诺,所以在捕获到此错误时会中断承诺,然后调用load。(在创建歌曲后立即加载歌曲在奇怪的情况下没有影响,只有在尝试播放时才会出现影响),以下是我使用的代码:

var playPromise = songToPlay.song.play();
// 在尚未支持此功能的浏览器中,playPromise不会被定义。
if (playPromise !== undefined) {
    playPromise.then(function() {
        // 自动播放已启动!
    }).catch(function(error) {
        console.log(error);
        console.log("尝试重新加载");
        songToPlay.song.load();
        songToPlay.song.play();
    });
}

代码的一部分取自"如何捕获播放错误" - https://stackoverflow.com/questions/38633615/javascript-audio-play-error

当然,用户至少要点击页面一次(我点击显示播放器区域,这样Chrome不会立即禁用音频播放)。

英文:

I also had trouble when dynamically added songs ended with "Uncaught (In promise): (DOMException) The element has no supported sources" . Where initially loaded songs on page refresh, worked just OK, but newly added NOT even thought its same code. I tried to discard old songs with "song.srcObj = null;" to help garbage collector, then I tried to always generate unique song url if some troubles happening when loading same song (element.song = new Audio("https://domain.cz" + element.file + "?" + new Date().getTime());)

What really helped was :

song.load();

More preciselly, since play is promise, so catching when this error breaks promise and then call load. (loading song just after it was created had no impact strangely, only when attempting to play), here is code I use :

                    var playPromise = songToPlay.song.play();
                    // In browsers that don’t yet support this functionality,
                    // playPromise won’t be defined.
                    if (playPromise !== undefined) {
                        playPromise.then(function() {
                            // Automatic playback started!
                        }).catch(function(error) {
                            console.log(error);
                            console.log(&quot;try to reload&quot;);
                            songToPlay.song.load();
                            songToPlay.song.play();
                        });
                    }

Part of code is taken from "how to catch play error" - https://stackoverflow.com/questions/38633615/javascript-audio-play-error

And of course user have to click on page at least once (I have click to show player area, so chrome wont disable audio playing straight ahead)

huangapple
  • 本文由 发表于 2020年10月22日 10:24:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64474338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定