簡體   English   中英

如何在 Vue 中檢索 mp3 或 wav 音頻文件的持續時間

[英]How to retrive the duration of a mp3 or wav audio file in Vue

當我上傳音頻文件以查看上傳的 mp3 或 wav 的持續時間時,我試圖實現,但我不知道如何在 vue 中做到這一點,有什么建議嗎? 我找到了這個腳本,但我不知道如何使用 vue 管理它。 任何幫助表示贊賞,謝謝。

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/

到目前為止我已經嘗試過但在控制台中我得到: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)
}

我已經這樣做了:

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)
    }

您必須使用 onloadmetadata 事件偵聽器來訪問音頻的持續時間。

myAudio.onloadedmetadata = ()=> {
  console.log(myAudio.duration)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM