我在谷歌驱动器中有一个MP3文件。有没有办法可以使用谷歌应用程序脚本获得该MP3文件的duraton?
答案 0 :(得分:1)
This页面显示了如何通过查看字节值从mp3文件中提取该信息。 所以我写了一个简短的例子并测试了它。它似乎与我到目前为止尝试的所有mp3文件一起正常工作,但不能保证它将始终有效。 getPlayTime函数以秒为单位返回播放时间。
function getPlayTime(file) {
var bitratesV1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
bitratesV2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
var bytes = file.getBlob().getBytes();
for(var pos = 0;pos < bytes.length; pos++) {
if(bytes[pos] === -1 && pos < bytes.length - 3 && (bytes[pos+1]&0xF0) === 0xF0) {
var isMpegVersion2 = (bytes[pos+1]&8) !== 8,
isLayer3 = (bytes[pos+1]&6) === 2,
bitRate = ((bytes[pos+2]&0xF0) >>> 4)&0xF;
if(!isLayer3) continue;
if(isMpegVersion2) bitRate = bitratesV2[bitRate];
else bitRate = bitratesV1[bitRate];
var playTime = bytes.length*8/(1000 * bitRate);
return playTime;
}
}
}
function test() {
var file = DriveApp.getFilesByName("music.mp3").next();
var playTime = getPlayTime(file);
Logger.log(playTime);
}
编辑: 这是一个希望更准确但也更慢的版本
function getRunTime(file) {
var playTime = 0, numFrames = 0;
var bitratesV1 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
bitratesV2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
var bytes = file.getBlob().getBytes();
for(var pos = 0;pos < bytes.length; pos++) {
if(bytes[pos] === -1 && pos < bytes.length - 3 && (bytes[pos+1]&0xF0) === 0xF0) {
var isMpegVersion2 = (bytes[pos+1]&8) !== 8,
isLayer3 = (bytes[pos+1]&6) === 2,
bitRate = ((bytes[pos+2]&0xF0) >>> 4)&0xF;
if(!isLayer3) continue;
if(isMpegVersion2) bitRate = bitratesV2[bitRate];
else bitRate = bitratesV1[bitRate];
var pt = bytes.length*8/(1000 * bitRate);
if(!isNaN(pt) && isFinite(pt)) {
playTime += pt;
numFrames++;
}
}
}
return playTime/numFrames;
}