<template> <div id="app"> <input type="file" @change="handleChange" /> <audio controls="true" @loadeddata="handleLoad" :src="url"> </audio> </div> </template> <script> import { secondsToTime, byteToText, getObjectURL } from "./util.js"; export default { name: "app", data() { return { url: "", }; }, methods: { handleLoad(event) { let duration = event.target.duration; console.log(duration, secondsToTime(duration)); }, handleChange(event) { let file = event.target.files[0]; console.log(file.name); console.log(file.size, byteToText(file.size)); let url = getObjectURL(file); console.log(url); this.url = url; }, }, }; </script>
用到的工具函数
// util.js /** * 秒 转文本显示 x时y分z秒 * @param {} secs */ export function secondsToTime(secs) { let hoursDiv = secs / 3600; // 向下取整 let hours = Math.floor(hoursDiv); let minutesDiv = (secs % 3600) / 60; let minutes = Math.floor(minutesDiv); // 向上取整 let seconds = Math.ceil((secs % 3600) % 60); if (seconds > 59) { seconds = 0; minutes = Math.ceil(minutesDiv); } if (minutes > 59) { minutes = 0; hours = Math.ceil(hoursDiv); } let timeStr = ""; if (hours > 0) { timeStr += `${hours}时`; } if (minutes > 0) { timeStr += `${minutes}分`; } if (seconds > 0) { timeStr += `${seconds}秒`; } return timeStr; } /** * 字节大小转显示文本 * @param {} size */ export function byteToText(size) { let mb = Math.floor(size / (1024 * 1024)); let kb = Math.floor(size / 1024); if (mb > 0) { return (size / (1024 * 1024)).toFixed(2) + "MB"; } else if (kb > 0) { return (size / 1024).toFixed(2) + "KB"; } else { return size.toFixed(2) + "B"; } } /** * 创建临时url * @param {*} file */ export function getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { // basic url = window.createObjectURL(file); } else if (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); } else if (window.webkitURL != undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file); } return url; }
参考