我正在使用 webgl 创建一个音频可视化器,并且一直在将 soundcloud 轨道集成到其中。我不想切换轨道,但我可以让我的可视化器工作并且音频中断,或者我可以让音频工作并且可视化器中断。
我能够使它工作的两种方法是
音频工作
- 删除音频元素
 - 将新的音频元素附加到正文
 - 触发播放
 
展示台工作
- 停止音频
 - 改变来源
 - 触发播放
 
当我让可视化器工作时,音频完全混乱了。缓冲区只是听起来不对,而且音频中有伪影(噪音、哔哔声和嗡嗡声)。
当我有音频工作时,当我打电话时analyser.getByteFrequencyData,我得到一个 0 的数组。我想这是因为分析仪没有正确连接。
音频工作的代码看起来像
$('#music').trigger("pause");
currentTrackNum = currentTrackNum + 1;
var tracks = $("#tracks").data("tracks")
var currentTrack = tracks[parseInt(currentTrackNum)%tracks.length];
// Begin audio switching
analyser.disconnect();
$('#music').remove();
$('body').append('<audio id="music" preload="auto" src="'+ currentTrack["download"].toString() + '?client_id=4c6187aeda01c8ad86e556555621074f"></audio>');
startWebAudio(),
(我认为我不需要pause电话。是吗?)
当我希望可视化器工作时,我使用此代码
currentTrackNum = currentTrackNum + 1;
var tracks = $("#tracks").data("tracks")
var currentTrack = tracks[parseInt(currentTrackNum)%tracks.length];
// Begin audio switching
$("#music").attr("src", currentTrack["download"].toString() + "?client_id=4c6187aeda01c8ad86e556555621074f");
$("#songTitle").text(currentTrack["title"]);
$('#music').trigger("play");
startWebAudio函数看起来像这样。
function startWebAudio() {
  // Get our <audio> element
  var audio = document.getElementById('music');
  // Create a new audio context (that allows us to do all the Web Audio stuff)
  var audioContext = new webkitAudioContext();
  // Create a new analyser
  analyser = audioContext.createAnalyser();
  // Create a new audio source from the <audio> element
  var source = audioContext.createMediaElementSource(audio);
  // Connect up the output from the audio source to the input of the analyser
  source.connect(analyser);
  // Connect up the audio output of the analyser to the audioContext destination i.e. the speakers (The analyser takes the output of the <audio> element and swallows it. If we want to hear the sound of the <audio> element then we need to re-route the analyser's output to the speakers)
  analyser.connect(audioContext.destination);
  // Get the <audio> element started  
  audio.play();
  var freqByteData = new Uint8Array(analyser.frequencyBinCount);
}
我怀疑分析仪没有正确连接,但我不知道要看什么才能弄清楚。我查看了frequencyByteData输出,这似乎表明某些东西没有正确连接。analyser变量是全局的。如果您想更多地参考代码,这里是它在 github 上的位置