HTML代码:
<input type="file" accept="audio/*" id="mp3">
<div id="output"></div>
JS代码:
// 秒转分钟的方法
const secondFormat = function (seconds) {
return `${Math.floor(seconds / 60)}分${Math.round(seconds % 60)}秒`;
};
// 列表渲染方法
const render = function (data) {
if (!data.duration) {
return;
}
output.innerHTML = `<section class="flex">
<img class="cover" src="${data.cover}">
<div class="info">
<data>
<b>${data.name}</b>
</data>
<p>
<time>${secondFormat(data.duration)}</time>
</p>
</div>
</section>`;
};
// 选择音频文件后
mp3.addEventListener('change', function (event) {
const file = event.target.files[0];
if (!file) {
return;
}
// 显示需要的数据
const data = {
name: file.name,
duration: 0,
cover: './cover-default.png'
};
// 读取文件为blob地址
const reader = new FileReader();
reader.onload = function (event) {
const url = event.target.result;
const audio = new Audio(url);
audio.addEventListener('loadedmetadata', function () {
data.duration = audio.duration;
render(data);
});
};
reader.readAsDataURL(file);
jsmediatags.read(file, {
onSuccess: function(tag) {
if (tag?.tags?.picture) {
// 转本地地址
data.cover = URL.createObjectURL(new Blob([new Uint8Array(tag.tags.picture.data).buffer]));
}
render(data);
},
onError: function(error) {
console.error(error);
render(data);
}
});
});