MDN’s new design is in Beta! A sneak peek:

Displaying a graphic with audio samples

この記事はまだボランティアによって 日本語 に翻訳されていません。ぜひ MDN に参加して翻訳を手伝ってください!
この記事を English (US) で読むこともできます。

The following example shows how to take samples from an audio stream and display them behind an image (in this case, the Mozilla logo), giving the impression that the image is built from the samples.


  <!DOCTYPE html>
    <title>JavaScript Spectrum Example</title>
    <audio id="audio-element"
           style="width: 512px;">
    <div><canvas id="fft" width="512" height="200"></canvas></div>
    <img id="mozlogo" style="display:none" src="mozilla2.png"></img>
      var canvas = document.getElementById('fft'),
          ctx = canvas.getContext('2d'),

      function loadedMetadata() {
        channels          = audio.mozChannels;
        rate              = audio.mozSampleRate;
        frameBufferLength = audio.mozFrameBufferLength;
        fft = new FFT(frameBufferLength / channels, rate);

      function audioAvailable(event) {
        var fb = event.frameBuffer,
            t  = event.time, /* unused, but it's there */
            signal = new Float32Array(fb.length / channels),

        for (var i = 0, fbl = frameBufferLength / 2; i < fbl; i++ ) {
          // Assuming interlaced stereo channels,
          // need to split and merge into a stero-mix mono signal
          signal[i] = (fb[2*i] + fb[2*i+1]) / 2;

        // Clear the canvas before drawing spectrum
        ctx.fillStyle = "rgb(0,0,0)"; 
        ctx.fillRect (0,0, canvas.width, canvas.height);
        ctx.fillStyle = "rgb(255,255,255)"; 

        for (var i = 0; i < signal.length; i++ ) {
          // multiply spectrum by a zoom value
          magnitude = signal[i] * 1000;

          // Draw rectangle bars for each frequency bin
          ctx.fillRect(i * 4, canvas.height, 3, -magnitude);
        ctx.drawImage(document.getElementById('mozlogo'),0,0, canvas.width, canvas.height);


      var audio = document.getElementById('audio-element');
      audio.addEventListener('MozAudioAvailable', audioAvailable, false);
      audio.addEventListener('loadedmetadata', loadedMetadata, false);



 このページの貢献者: jswisher, sebmozilla
 最終更新者: jswisher,