我有一个网页需要播放mp3文件(如果存在)
但是我只能使用javascript ...
我尝试了另一种方法,但是仍然无法检查文件是否存在。
有时可以在IE中使用,
但不适用于Chrome
于20200731更新
我已经更新了我的代码
现在我用2个函数更新了我的代码
executeIfFileExist <-检查文件是否存在
playme <-播放mp3,这很好,我现在可以播放音乐。
检查文件存在功能仍无法正常工作。
即使我的文件存在于服务器中,播放器仍然无法显示。
任何人都可以帮助我。
非常感谢。
<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>
最佳答案
您可以使用一个功能来检查文件是否存在,请尝试一下!
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === this.DONE) {
callback();
}
};
xhr.open('HEAD', src);
}
关于javascript - 仅使用javascript检查音频文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63145288/