我想通過輸入檔案閱讀器加載音頻檔案,然后能夠播放它...
以下是創建檔案 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;
}
uj5u.com熱心網友回復:
您不需要任何轉換,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>
uj5u.com熱心網友回復:
<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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334103.html
標籤:javascript 查询
