I'm having a small webpage with embedded soundcloud elements, and I would like to make a frequency spectrum analyzer thing. So far I've succeeded in making one that just uses a local sound file, but i can't figure out how to get audio data from the embedded elements.
Is there a way to extract sound data from the embedded elements?
If this is not a simple task, it would be equally satisfying to be able to analyze the sound just currently being played in the browser, if at all possible.
Thanks in advance : )
Code (Not really written by me, I found most of it from tutorials)
The HTML (embedded soundcloud tag)
<iframe id="em1" width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/144737157&auto_play=false&hide_related=false&visual=true"></iframe>
The JS, where i wish to somehow attach the SoundCloudAudioSource to either the embedded tag or the entire browser window.
var SoundCloudAudioSource = function(audioElement) {
var player = document.getElementById(audioElement);
var self = this;
var analyser;
var audioCtx = new (window.AudioContext || window.webkitAudioContext); // this is because it's not been standardised accross browsers yet.
analyser = audioCtx.createAnalyser();
analyser.fftSize = 256; // see - there is that 'fft' thing.
var source = audioCtx.createMediaElementSource(player); // this is where we hook up the <audio> element
source.connect(analyser);
analyser.connect(audioCtx.destination);
var sampleAudioStream = function() {
// This closure is where the magic happens. Because it gets called with setInterval below, it continuously samples the audio data
// and updates the streamData and volume properties. This the SoundCouldAudioSource function can be passed to a visualization routine and
// continue to give real-time data on the audio stream.
analyser.getByteFrequencyData(self.streamData);
// calculate an overall volume value
var total = 0;
for (var i = 0; i < 80; i++) { // get the volume from the first 80 bins, else it gets too loud with treble
total += self.streamData[i];
}
self.volume = total;
};
setInterval(sampleAudioStream, 20); //
// public properties and methods
this.volume = 0;
this.streamData = new Uint8Array(128); // This just means we will have 128 "bins" (always half the analyzer.fftsize value), each containing a number between 0 and 255.
this.playStream = function(streamUrl) {
// get the input stream from the audio element
player.setAttribute('src', streamUrl);
player.play();
}
};