最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Getting the duration of an MP3 file with JavaScript using "Web Audio API" and "AudioContext&am

programmeradmin1浏览0评论

Is there any way to get the duration of an MP3 file with JavaScript using Web Audio API and AudioContext?

I can get that duration with the HTML5 element: <audio/> but I want to use the Web Audio API.

Below is the code I have so far. If you have any suggestion, please, fork my code on: CodePen.io and post the link.

CodePen.io code:

window.addEventListener('load', () => {
	const URL = '.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>

Is there any way to get the duration of an MP3 file with JavaScript using Web Audio API and AudioContext?

I can get that duration with the HTML5 element: <audio/> but I want to use the Web Audio API.

Below is the code I have so far. If you have any suggestion, please, fork my code on: CodePen.io and post the link.

CodePen.io code: https://codepen.io/anon/pen/QZwyqd

window.addEventListener('load', () => {
	const URL = 'https://www.tophtml./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>

Thanks!

Share Improve this question asked Sep 29, 2018 at 2:32 davidespdavidesp 3,99213 gold badges46 silver badges84 bronze badges 1
  • I am not sure if it's possible to use AudioContext without audio tag. so even if it's possible to get the duration using AudioContext you will still end up using the audio tag – evgeni fotia Commented Sep 29, 2018 at 10:26
Add a ment  | 

2 Answers 2

Reset to default 3

Yes, it's possible to do this and without an audio tag. You need to download audio file using Ajax/XMLHttpRequest and decode the file like this:

// 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./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;

}

Once you've got your AudioBuffer it has a duration property. This is a double representing the duration in seconds.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论