fbricker / muses

The Flash MP3/OGG/AAC Live Stream Player
https://www.muses.org
63 stars 18 forks source link

Connect radio api to analyzer - canvas #17

Closed JakubKrizka closed 8 years ago

JakubKrizka commented 9 years ago

Hi, I want to connect audio/radiostream from your MUSES radio API to analyzer, here is function demo, with stream from SoundCloud: http://jakubkrizka.cz/radio.html

(in chrome don't working change currentTime() and firefox limited to 30 FPS)

<html>
    <head>
        <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0">
        <style>
            body {background-color: black}
            div#mp3_player{ width:600px; margin:33px auto; text-align: center}
            div#mp3_player > div > audio { width:100%; }
            div#mp3_player > canvas{ width:100%; height:333px; text-align: center }
        </style>
        <script>
            // define RequestAnimationFrame()
            (function() {
                var lastTime = 0,
                        vendors = ['ms', 'moz', 'webkit', 'o'],
                // Feature check for performance (high-resolution timers)
                        hasPerformance = !! (window.performance && window.performance.now);

                for (var x = 0, max = vendors.length; x < max && !window.requestAnimationFrame; x += 1) {
                    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
                    window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
                            || window[vendors[x] + 'CancelRequestAnimationFrame'];
                }
                if (!window.requestAnimationFrame) {
                    console.log('Polyfill');
                    window.requestAnimationFrame = function(callback, element) {
                        var currTime = new Date().getTime();
                        var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                        var id = window.setTimeout(function() {
                            callback(currTime + timeToCall);
                        }, timeToCall);
                        lastTime = currTime + timeToCall;
                        return id;
                    };
                }
                if (!window.cancelAnimationFrame) {
                    window.cancelAnimationFrame = function(id) {
                        clearTimeout(id);
                    };
                }
                // Add new wrapper for browsers that don't have performance
                if (!hasPerformance) {
                    console.log("Browser doesn't have performance");
                    // Store reference to existing rAF and initial startTime
                    var rAF = window.requestAnimationFrame,
                            startTime = +new Date;
                    // Override window rAF to include wrapped callback
                    window.requestAnimationFrame = function(callback, element) {
                        // Wrap the given callback to pass in performance timestamp
                        var wrapped = function(timestamp) {
                            // Get performance-style timestamp
                            var performanceTimestamp = (timestamp < 1e12) ? timestamp : timestamp - startTime;

                            return callback(performanceTimestamp);
                        };
                        // Call original rAF with wrapped callback
                        rAF(wrapped, element);
                    }
                }
            })();
            // Create a new instance of an audio object and adjust some of its properties
            var audio = new Audio();
            // import audio stream or file
            audio.src = 'http://api.soundcloud.com/tracks/215138926/stream?client_id=17a992358db64d99e492326797fff3e8';
            // audio.src = 'color128.mp3';
            audio.crossOrigin = "anonymous";
            audio.controls = true;
            audio.loop = false;
            audio.autoplay = true;
            // audio.addEventListener('ended', foo);
            // Establish all variables that your Analyser will use
            var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height, grd;
            // Initialize the MP3 player after the page loads all of its HTML into the window
            window.addEventListener("load", initMp3Player, false);
            function initMp3Player(){
                document.getElementById('audio_box').appendChild(audio);
                context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext)(); // AudioContext object instance
                analyser = context.createAnalyser(); // AnalyserNode method
                canvas = document.getElementById('analyser_render');
                ctx = canvas.getContext('2d');
                // Re-route audio playback into the processing graph of the AudioContext
                source = context.createMediaElementSource(audio);
                source.connect(analyser);
                analyser.connect(context.destination);
                frameLooper();
            }
            // frameLooper() animates any style of graphics you wish to the audio frequency
            // Looping at the default frame rate that the browser provides(approx. 60 FPS)
            function frameLooper(){
                window.requestAnimationFrame(frameLooper);
                fbc_array = new Uint8Array(analyser.frequencyBinCount);
                analyser.getByteFrequencyData(fbc_array);
                ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
                // set up nice Gradient
                grd = ctx.createLinearGradient(0, 200, 0, 0);
                grd.addColorStop(0, "#51FF00");
                grd.addColorStop(1, "#FF0000");
                ctx.fillStyle = grd;
                //ctx.fillStyle = '#fff'; // Color of the bars
                bars = 1010;
                for (var i = 0; i < bars; i++) {
                    bar_x = i * 1;
                    bar_width = 1;
                    bar_height = -(fbc_array[i] / 2);
                    //  fillRect( x, y, width, height ) // Explanation of the parameters below
                    ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
                }
            }
        </script>
    </head>
    <body>
        <div id="mp3_player">
            <div id="audio_box"></div>
            <canvas id="analyser_render"></canvas>
            <iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/215138926&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false&amp;visual=true"></iframe>
        </div>
    </body>
</html>

can you help me please? :+1:

JakubKrizka commented 9 years ago

@fbricker