【问题标题】:Cant load music file when page loads页面加载时无法加载音乐文件
【发布时间】:2019-06-05 21:23:39
【问题描述】:

我正在制作一个网站,我想在我的页面刷新时加载一个 MP3 文件,但不知何故它无法播放。

<body>
    <audio id="kofi" autoplay="autoplay">
        <source src="kofi.mp3" type="audio/mp3">
    </audio>

<script type="text/javascript">

window.onload = function(){
document.getElementById('kofi').play(); // On this line I get error "Uncaught (in promise) DOMException"
    }
</script>
<body>

【问题讨论】:

    标签: javascript


    【解决方案1】:

    play() / pause() 功能正在使用Promises,这就是为什么它不能按预期工作的原因。从this reference,我可以做下面的例子:

    <script>
      window.onload = function() {
        var song = document.getElementById('kofi');
        // This will allow us to play song later...
        song.load();
        fetchSongAndPlay();
      }
    
      function fetchSongAndPlay() {
        fetch('kofi.mp3')
        .then(response => response.blob())
        .then(blob => {
          song.srcObject = blob;
          return song.play();
        })
        .then(_ => {
          // Music playback started ;)
        })
        .catch(e => {
          // Music playback failed ;(
        })
      }
    </script>
    

    【讨论】:

    • margin_collapsing.html:113 Fetch API 无法加载 file:///C:/Users/Administrator/Desktop/Folder/kofi.mp3。对于 CORS 请求,URL 方案必须是“http”或“https”。
    • @Jimmy 您必须将文件加载到同一台服务器上。看到这个问题。 stackoverflow.com/questions/48728334/… 您可以运行 localhost 服务器或将文件移动到实际服务器。如果您有任何其他问题,我建议您提出一个新问题。希望这会有所帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多