使用“ Web Audio API”和“ AudioContext”使用JavaScript获取MP3文件的持续时间

时间:2018-09-29 02:32:39

标签: javascript html web-audio web-audio-api audiocontext

是否可以使用MP3JavaScriptWeb Audio API获取AudioContext文件的持续时间?

我可以使用HTML5元素来获得该持续时间:<audio/>,但是我想使用Web Audio API

下面是我到目前为止的代码。如果您有任何建议,请将我的代码添加到CodePen.io上并发布链接。

CodePen.io代码:https://codepen.io/anon/pen/QZwyqd

window.addEventListener('load', () => {
	const URL = 'https://www.tophtml.com/snl/15.mp3';
	let url = URL + '?nocache='+(new Date()).getTime();
	let audio = document.querySelector('audio');
	audio.setAttribute('src', url);
	audio.addEventListener('durationchange', function() {
		log('way 1: ' + this.duration);
	});
	getAudioDurationWithAudioContext().then((duration) => {
		log('way 2: ' + duration);
	});
	log('...');
});
function getAudioDurationWithAudioContext() {
	// PLEASE, IMPLEMENT THIS FUNCTION AND "FORK" THIS CODE
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve('???.???');
		}, 1000);
	});
}
function log(text, append = true) {
	let logger = document.querySelector('.logger');
	if (text == '') {
		logger.innerHTML = '';
		return;
	}
	if (!append)
		logger.innerHTML = '';
	let entry = document.createElement('div');
	entry.innerHTML = text;
	logger.appendChild(entry);
}
.logger {
	display: inline-block;
	font-family: monospace;
	white-space: pre;
	font-size: 13px;
	margin-top: 10px;
	background-color: #d4e4ff;
}
.logger {
	padding: 4px;	
}
.divider {
	border-top: 1px solid #ccc;
	margin: 10px 0;
}
  
<div>
	<audio controls preload="auto"></audio>
</div>

<div class="logger"></div>

谢谢!

2 个答案:

答案 0 :(得分:0)

一旦您拥有AudioBuffer,它就会具有duration属性。这是一个以秒为单位的持续时间。

答案 1 :(得分:0)

是的,可以在没有音频标签的情况下执行此操作。您需要使用Ajax / XMLHttpRequest下载音频文件并像这样解码文件:

// Step 1: We need AudioContext instance to decode audio files.
var context = new AudioContext();


// Step 2: Download a .mp3 file using AJAX
var request = new XMLHttpRequest();
request.addEventListener('load', fileLoaded);
request.open('GET', 'https://www.tophtml.com/snl/15.mp3');
request.responseType = 'arraybuffer';
request.send();


// Step 3: File downloaded, need to be decoded now.
function fileLoaded() {
    if (request.status < 400)
        context.decodeAudioData(request.response, fileDecoded);
}


// Step 4: File decoded, we can get the duration.
function fileDecoded(audioBuffer) {

    // This is the duration you want, in seconds:
    audioBuffer.duration;

}