我在Visualizations with Web Audio API上看到了一个解释如何进行可视化的页面。我尝试了那些确切的代码并得到了诸如“ReferenceError:stream is not defined”等错误。有没有办法使音频元素的可视化?只有它适用于FireFox才有意义。
答案 0 :(得分:2)
简单的方法是:
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
}
答案 1 :(得分:0)
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库。