How to show audio preview while playing? [duplicate]

0

Hi stackoverflow folks,

You have an example GitHub , showing audio preview.

How to do this in asp.net mvc?

View:

<audio controls style="width: 375px;height:225px;">
    <source src="@Url.Action("StreamUploadedSong", "Account", new { id = Model.Id })" type="audio/mp3" />
    Your browser does not support the audio element.
</audio>

Image example:

Where the red rectangle is, it is to show preview while playing audio.

Any ideas?

    
asked by anonymous 30.11.2016 / 22:15

1 answer

2

using the analyserNode and the canvas gives to do so:

var w = 800;
var h = 600;
var total_bars = 16;
var sampleSize = 2048;
var background_color = "#231f20";
var bars_color = "#f0ad00";
var gap = 5;
var bar_width = (w/total_bars) - (gap * (total_bars-1) / total_bars);
var bar_height = getBarHeight(h);
var sound_path = 'song.m4a';

var sound = new Audio(sound_path);
sound.play();

var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');

var audioCtx = new(window.AudioContext || window.webkitAudioContext);

var sourceNode = audioCtx.createMediaElementSource(sound);
var analyser = audioCtx.createAnalyser();
analyser.fftSize = total_bars * 2;
analyser.smoothingTimeConstant = 0.65;

function getBarHeight(h) {
    var bar_height = 0;
    for (var i = 0; i < h; i += 256) {
        bar_height += 1;
    }
    return bar_height;
} 

function update() {
    var frequencyData = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(frequencyData);
    drawFrame(frequencyData);
    requestAnimationFrame(update);
};

function drawFrame(heights) {
    ctx.fillStyle = background_color;
    ctx.fillRect(0,0,w,h);
    ctx.fillStyle = bars_color;
    var rx = 0;
    for (var i in heights) {
        var rw = bar_width;
        var rh = heights[i] * bar_height;
        var ry = h - rh;
        if ( i > 0 ) {
            rx += gap;
        }
        ctx.fillRect(rx, ry, rw, rh);
        rx += rw;
    }
}

sourceNode.connect(analyser);
analyser.connect(audioCtx.destination);
update();
    
01.12.2016 / 01:47