【问题标题】:checking audio file exists with javascrip only仅使用 javascript 检查音频文件是否存在
【发布时间】:2020-11-18 13:16:17
【问题描述】:

我有一个需要播放 mp3 文件的网页(如果存在) 但我只能用javascript...

我尝试了不同的方法,但我仍然无法检查文件是否存在.. 它有时在 IE 中有效, 但不能在 chrome 中工作


更新于 20200731

我已经更新了我的代码

现在我用 2 个函数更新了我的代码 executeIfFileExist

检查文件存在功能仍然无法正常工作。 即使我的文件存在于服务器中,播放器仍然没有显示。

任何人都可以帮助我。 非常感谢。

<script>
function executeIfFileExist(src, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", src, true); 
  xhr.onreadystatechange = function () {
    if (this.readyState === this.DONE) {
      callback();
    }
  };
  xhr.open('HEAD', src);
}

function playme(mp3file)    {
    //$("#playAudio").attr('src',mp3file).autoplay;
    $('#playAudio').show();
    $("#playAudio").attr('src',mp3file).play;
}
function showTips(url,event){
    $('#tipsimg').attr('src', url);
    // start
    $('#playAudio').hide();
    mp3file = url.substr(0, url.lastIndexOf(".")) + ".mp3";
    mp3file = '01.mp3';
    alert(mp3file);
    // $("#playAudio").attr('src',mp3file).play();
    // playme(mp3file);
    executeIfFileExist(mp3file,playme);
    // end
    $('.tips').show();      

    //event.preventDefault();
}

$(document).ready(function(){
    showTips('01.png',null);
})
</script>

<div class="tips">
  <img src="" data="image1" id="tipsimg" />
  <br />
  <audio id="playAudio" controls autoplay>
    <source src="" type="audio/mpeg" />
    Your browser does not support the audio element.
  </audio>
</div>

【问题讨论】:

  • 你尝试添加这个吗? sound.onload = (event) =&gt; { ... }
  • 已添加但无法正常工作.. :(

标签: javascript file audio mp3 exists


【解决方案1】:

我找到了答案并尝试了自己,至少它有效(如果找不到,请隐藏音频标签) 但是如果文件不存在它仍然会显示js错误

希望对你有帮助

function executeIfFileExist(src, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
     callback(src);
    }
  };
  xhr.open("GET", src, true); 
  xhr.responseType = 'blob';  // add these line will loop until the file is ready
  xhr.send();  // add these line will loop until the file is ready
}

function playme(mp3file)    {
    $('#playAudio').hide();
    $('#playAudio').show();
    $("#playAudio").attr('src',mp3file).play;
}

【讨论】:

    【解决方案2】:

    你可以有一个检查文件是否存在的功能,试试这个!

    function executeIfFileExist(src, callback) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function () {
        if (this.readyState === this.DONE) {
          callback();
        }
      };
      xhr.open('HEAD', src);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 2013-07-17
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 2014-02-22
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多