HTML5音频可视化

HTML5 Audio Visualization?

本文关键字:可视化 音频 HTML5      更新时间:2023-09-26

我看到了一个关于Web Audio API的可视化页面,其中解释了如何制作可视化。我尝试了确切的代码,得到了"ReferenceError: stream is not defined"等错误。是否有一种方法可以从音频元素中制作出可视效果?只有在FireFox上运行才重要。

简单的方法是:

    let audio = document.getElementById("yourAudioElement");
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    let ctx = new window.AudioContext();
    // add the audio element node as source for AudioContext instance
    let sourceNode = ctx.createMediaElementSource(audio);
    // if you wish to visualize the audio then you will have to connect this to an analyzer
    let analyzer = ctx.createAnalyser();
    analyser.smoothingTimeConstant = 0.6;
    analyser.fftSize = 512; // frequency sample size 
    // set frequency data
    let frequencyData = new Uint8Array(analyser.frequencyBinCount);
    // connect source node to analyser to collect frequency data
    sourceNode.connect(this.analyser);
    // connect this source to the audio output (your speaker device)
    sourceNode.connect(ctx.destination);
    // you can then start your audio as below
    audio.play();
    // then you can animate the frequence data by calling requestAnimationFrame()
    // this method allows you to keep updating your visualization by frames
    function renderFrame() {
        // you need to check whether audio is playing here to control this recursive call
        requestAnimationFrame(renderFrame);
        analyser.getByteFrequencyData(frequencyData);
        // then just use your imagination to animate the frequency data by frame
        // you can update your canvas here
    }
window.AudioContext = window.AudioContext || window.webkitAudioContext;
// Create the instance of AudioContext
var context = new AudioContext();
navigator.getUserMedia = navigator.getUserMedia       ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;
// Access microphone
var medias = {audio : true, video : false};
/**
 * @param {MediaStream|LocalMediaStream} stream
 */
var successCallback = function(stream) {
    // Create the instance of MediaStreamAudioSourceNode
    var source = context.createMediaStreamSource(stream);
    // code for visualization
    // do something ...
};
/**
 * @param {NavigatorUserMediaError|MediaStreamError} error
 */
var errorCallback = function(error) {
    console.error(error);
};
navigator.getUserMedia(medias, successCallback, errorCallback);
XSound.js是一个非常有用的Web Audio API库。