Reputation: 49
Im trying to achive when i upload an audio file to see te duration of the uploaded mp3 or wav, but i don't know how to do that in vue, any sugestions ? I have find this script but i don't have a clue how to manage'it with vue. Any help appreciated, thanks.
Javascript:
var objectUrl;
$("#audio").on("canplaythrough", function(e){
var seconds = e.currentTarget.duration;
var duration = moment.duration(seconds, "seconds");
var time = "";
var hours = duration.hours();
if (hours > 0) { time = hours + ":" ; }
time = time + duration.minutes() + ":" + duration.seconds();
$("#duration").text(time);
URL.revokeObjectURL(objectUrl);
});
$("#file").change(function(e){
var file = e.currentTarget.files[0];
$("#filename").text(file.name);
$("#filetype").text(file.type);
$("#filesize").text(file.size);
objectUrl = URL.createObjectURL(file);
$("#audio").prop("src", objectUrl);
});
http://jsfiddle.net/derickbailey/s4P2v/
What i have tried so far but in console i get: 0:00:
<input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
<button @click="submitAudioFile"> SUBMIT</button>
handleFileUpload () {
this.file = this.$refs.file.files[0]
},
submitAudioFile () {
let objectUrl = ''
const myAudio = this.$refs.file.files[0]
objectUrl = URL.createObjectURL(myAudio)
const seconds = myAudio.duration
const duration = moment.duration(seconds, 'seconds')
let time = ''
const hours = duration.hours()
if (hours > 0) { time = `${hours }:` }
time = `${time + duration.minutes() }:${ duration.seconds()}`
console.log(time)
URL.revokeObjectURL(objectUrl)
}
Upvotes: 1
Views: 1826
Reputation: 98
You have to use onloadmetadata event listener to access duration of audio.
myAudio.onloadedmetadata = ()=> {
console.log(myAudio.duration)
}
Upvotes: 1
Reputation: 49
I have done this with:
duration () {
const files = document.getElementById('file').files
const file = files[0]
const reader = new FileReader()
const audio = document.createElement('audio')
reader.onload = function (e) {
audio.src = e.target.result
audio.addEventListener('durationchange', function () {
const seconds = audio.duration
const duration = moment.duration(seconds, 'seconds')
let time = ''
const hours = duration.hours()
if (hours > 0) { time = `${hours}:` }
time = `${time + duration.minutes() }:${duration.seconds()}`
console.log(time)
}, false)
audio.addEventListener('onerror', function () {
alert('Cannot get duration of this file.')
}, false)
}
reader.readAsDataURL(file)
}
Upvotes: 0