簡體   English   中英

跨瀏覽器HTML5音頻播放器

[英]Cross-browser HTML5 audio player

I am using audio tag to play a wav audio, My url is genereted by URL.createObjectURL() and the url is like blob:http://localhost/9fa2ef06-ade6-4027-89f8-06cd2c176405

由於 url 沒有擴展,我對 safari 有一些問題

以下代碼適用於 chrome,不適用於 safari(音頻播放器已禁用)

<audio src="MY_BLOB_URL" type="audio/wav">
</audio>

以下代碼適用於 safari 而不適用於 chrome

<audio controls>
  <source src="MY_BLOB_URL" type="audio/wav">
</audio>

我嘗試了以下奇怪的代碼,但找不到在兩種瀏覽器上都可以使用的任何方法

<audio src="MY_BLOB_URL" type="audio/wav">
  <source src="MY_BLOB_URL" type="audio/wav">
</audio>

這里有什么問題? 我怎樣才能擁有一個單代碼的跨瀏覽器 HTML5 音頻播放器?

我已經使用 Chrome、Edge 和 Firefox 在 Windows PC 上測試了以下代碼。
希望它也適用於 Safari。

PS:對於未來的讀者,此代碼也適用於 MP3 blob(設置為accept=".mp3" )。

<!DOCTYPE html>
<html><head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> </head>

<body>

<div style="z-index: 1; overflow:hidden; position: absolute; top: 100px; left: 50px">
<audio id="tag_Audio1" controls>
<source type="audio/wav">
</audio>
</div>

<br><br><br><br>

<div style="z-index: 1; overflow:hidden; position: absolute; top: 10px; left: 50px">
<p> Choose an WAV file...</p>
<input type="file" id="choose_media" accept=".wav" />
</div>

<script>

var file; var reader;
var tmpElement; //# is reference to aTag for holding image content.
var file_Blob; //# is reference to file BLOB (data of selected file).

const  myAudio = document.getElementById("tag_Audio1");
document.getElementById("choose_media").addEventListener("change", onFile_Selected, false);

function onFile_Selected(evt) 
{
    file = evt.target.files[0]; //# access to selected file
    
    reader = new FileReader();
    reader.readAsDataURL(file); //# load selected file as Blob
    reader.addEventListener("loadend", onFile_Loaded, false);
}

function onFile_Loaded(evt) 
{
    if (evt.target.readyState == FileReader.DONE) 
    {
        //# remove any current SRC
        myAudio.removeAttribute("src");
        
        //# create blob
        file_Blob = (window.URL || window.webkitURL).createObjectURL(file);
        
        //# apply blob & test play
        myAudio.setAttribute("src", file_Blob);
        myAudio.load();
        myAudio.play();
    }   
}

</script>

</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM