Vue试听本地磁盘的音频
问题描述: 项目中涉及到一个报警声音选择, 有一个试听的功能,
试听后觉得可以才把file文件传给服务端,需要前端自己实现试听本地磁盘的音频;
主要代码如下:
<template>
<div>
<input
type="file"
ref="fileInput"
@change="handleFileChange"
>
<audio ref="audioPlayer"></audio>
<button @click="playAudio">播放音频</button>
</div>
</template>
<script>
export default {
data() {
return {
audioPath: "",
};
},
mounted() {},
methods: {
handleFileChange() {
const file = this.$refs.fileInput.files[0];
console.log(file);
this.audioPath = URL.createObjectURL(file);
console.log(this.audioPath);
},
playAudio() {
const audio = this.$refs.audioPlayer;
audio.src = this.audioPath;
audio.play();
},
},
};
</script>
<style lang='css' scoped>
</style>
核心就是利用 URL.createObjectURL将文件传化成一个可播放的url路径