Reputation: 317
<!DOCTYPE html>
<html>
<head>
<title>createMediaElementSource test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var audioContext, mediaElementSource, analyzer, analyzerBytes;
function initAudio(audio) {
if (!audioContext) {
audioContext = new(window.AudioContext || window.webkitAudioContext)();
analyzer = audioContext.createAnalyser();
analyzer.connect(audioContext.destination);
mediaElementSource = audioContext.createMediaElementSource(audio);//when adding this line it breaks
mediaElementSource.connect(analyzer);
analyzerBytes = new Uint8Array(analyzer.frequencyBinCount);
window.setInterval(function() {
var min = 0,
max = 0,
sum = 0,
avg = 0;
analyzer.getByteFrequencyData(analyzerBytes);
for (var i = 0; i < analyzer.frequencyBinCount; i++) {
min = Math.min(min, analyzerBytes[i]);
max = Math.max(max, analyzerBytes[i]);
sum += analyzerBytes[i];
}
avg = Math.round(sum / analyzer.frequencyBinCount);
document.getElementById('analyzerData').textContent = "" + min + "/" + max + "/" + avg;
}, 100);
}
}
</script>
</head>
<body>
<audio controls src="song.mp3" onplay="initAudio(this)"></audio>
<div>
Analyzer Data: min/max/avg: <span id="analyzerData"></span>
</div>
</body>
</html>
I just using the createMediaElementSource offline but failed, so I looked up how other people we doing it. The exact same code from above was working online, but when I download it it runs into the same problems I had before. When adding the actual createmediaelementsource line the audio tag stops working. Console gives no errors. The code snippet obviously won't work here because the audio src isn't here but I added the snipped in so you could see the code. http://ruurd.alecm.nl/why.html < works just fine, but offline it doesn't. So why doesn't it work offline? I need it to work offline for this project.
Upvotes: 1
Views: 1200
Reputation: 6748
You didn't say, but I suspect you're using Firefox or possibly Safari. It actually worked for me when I downloaded your page and loaded it locally in Chrome. But I think this is a bug in Chrome.
Unfortunately, local media files (i.e. file:// URLs) are always treated as being in a different domain from the web page that contains them, even if the web page is also a local file. And that means you run into this problem:
Why aren't Safari or Firefox able to process audio data from MediaElementSource?
It basically means you have to load the page from a web server, not from a file. You can set up a local web server on your own machine to serve local files.
Upvotes: 2