[英]JavaScript / HTML5 audio: play mp3 file loaded by user via file selector in Android Chrome
[英]How to play audio loaded via file input
我想通過輸入文件閱讀器加載音頻文件,然后能夠播放它...
以下是創建文件 blob 並將音頻源分配給此 blob 的過程:
fileInput.on('change', readFile);
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
const binaryData = e.target.result;
const binary = convertDataURIToBinary(binaryData);
const blob = new Blob(binary, {type: input.files[0].type });
console.log('inserting blobXX', blob);
recordedAudioComponent.src = URL.createObjectURL(blob);
data.instructAudios[component] = blob;
console.log('recordedAudioComponent.src', recordedAudioComponent.src);
}
reader.readAsDataURL(input.files[0]);
}
}
這是上面代碼在控制台上的結果:
現在我正在嘗試播放recordedAudioComponent
,它是一個帶有源的音頻標簽嗎?
const recordedAudioComponent = document.getElementById(`recordedAudio-instruct-${component}`);
console.log(recordedAudioComponent)
recordedAudioComponent.play();
這是它產生的錯誤:
我該如何解決這個問題並播放音頻?
編輯:這是在第一個代碼中獲取 blob 的函數:
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
您不需要任何轉換,blob 實際上與文件本身非常相似,並且 URL.createObjectURL 方法接受文件作為參數,從瀏覽器播放音頻文件所需要做的就是將 src 屬性設置為 url創建,是這樣的:
<body> <input style="display: block;" type="file" onchange="loadAudioFile(this)"> <audio src=" " id="track" controls> </audio> <script> function loadAudioFile(e) { const url = URL.createObjectURL(e.files[0]); document.getElementById('track').setAttribute('src', url); } </script> </body>
<input type="file" name="fileInput" id="fileInput">
<script>
const fileInput = document.querySelector('#fileInput');
fileInput.onchange = readFile;
/** @type {AudioNode} */
const audio = document.createElement( 'audio' );
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onloadend = function (e){
audio.src = e.target.result;
audio.play();
}
reader.readAsDataURL(input.files[0]);
}
}
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.