“滄海一聲唱 滔滔兩岸潮
浮沉隨浪歌舞今朝
蒼天唱 紛紛世上潮
誰負(fù)誰勝出天知曉
江山唱 煙雨遙
濤浪淘盡紅塵俗世幾多嬌
清風(fēng)唱 竟惹寂寥
豪情還剩了一襟晚照
蒼生唱 不再寂寥
豪情仍在癡癡唱唱”
—— 題記,《滄海一聲唱》
正文
在上文 JS | Web Audio API (上) 你的音譜 中,我們了解到Audio API簡單的音頻知識(shí)點(diǎn),重在理論,今天搞點(diǎn)有趣的試驗(yàn),偏重實(shí)踐。大家知道,光有光譜,電磁波有頻譜,音樂呢?當(dāng)然也有自己的譜。想奧斯特實(shí)驗(yàn)揭示電流周圍存在磁場,分散的鐵屑顯現(xiàn)磁鐵的磁場分布,那音樂如何看到自身的頻率,所以,本文的主題來了,音頻可視化,讓你的音樂浪起來。先附上效果圖,接下來會(huì)主要圍繞效果例子出發(fā):

這種音波似的效果,我們可能會(huì)在音樂室或音樂人或音樂播放器那兒看到,并不少見,當(dāng)?shù)谝淮伟l(fā)現(xiàn)可以實(shí)現(xiàn)時(shí),ohMyGod,震撼,神奇,而對(duì)于喜歡的事物,總會(huì)想為我所用,閑話不多說,一起看看它是怎么實(shí)現(xiàn)的吧。根據(jù)已有的web audio API知識(shí),實(shí)踐音頻可視化,自我總結(jié),步驟大致分為以下幾步:
- 創(chuàng)建音頻環(huán)境
- 獲取音頻,創(chuàng)建buffer節(jié)點(diǎn)
- 解碼音頻,分析音頻
- 連接音頻輸入輸出
- canvas繪制頻譜
- 連接播放
創(chuàng)建音頻環(huán)境AudioContext
音頻環(huán)境是所有音效操作的前提,好比canvas的畫布,先有個(gè)做畫之地,再來筆墨橫姿
// Webkit/blink browser require a prefix, and it needs the window object specifically declared to work in Safari
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
// declare new audio context
try {
var audioCtx = new AudioContext();
} catch (e) {
alert('Your browser does not support AudioContext!');
console.log(e);
}
獲取音頻,創(chuàng)建buffer節(jié)點(diǎn)
首先獲取音頻,也就是說拿到這個(gè)素材輸入之后,我們可以趕制加工,這里通過XMLHttpRequest獲取,將請(qǐng)求的返回類型設(shè)為“arraybuffer”,方便音頻數(shù)據(jù)處理;另外,創(chuàng)建音頻節(jié)點(diǎn)createBufferSource,來獲取輸入的音頻。
// use XHR to load an audio track, and
// decodeAudioData to decode it and stick it in a buffer.
// Then we put the buffer into the source
var xhr = new XMLHttpRequest();
// 初始化 HTTP 請(qǐng)求參數(shù), 配置請(qǐng)求類型,文件路徑等
xhr.open('GET', 'audio/music1.mp3');
// 將responseType設(shè)為arraybuffer,二進(jìn)制數(shù)據(jù)
xhr.responseType = "arraybuffer";
// 獲取完成,對(duì)音頻進(jìn)一步操作,解碼
xhr.onload = function() {
var audioData = xhr.response;
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
var source = audioCtx.createBufferSource();
……
}
解碼音頻,分析音頻
好的,現(xiàn)在我們拿到了音樂,但計(jì)算機(jī)仍然不懂,需要對(duì)其進(jìn)行解碼decodeAudioData。
一看到解碼后的數(shù)據(jù),我們不能讓計(jì)算機(jī)“啪啪啪”就來吧,觀個(gè)全局,做個(gè)自我分析,createAnalyser。
audioCtx.decodeAudioData(audioData, function(buffer) {
// set the buffer in the AudioBufferSourceNode
source.buffer = buffer;
// create audio node to play the audio in the buffer
var analyser = audioCtx.createAnalyser();
}
連接音頻輸入輸出
必經(jīng)之路,input ——> 音頻處理 ——> 輸出,connect連接。
// connect the analyser to the destination(the speaker), or we won't hear the sound
// from audioCtx.createBuffer, or audioCtx.decodeAudioData
source.connect(analyser);
analyser.connect(audioCtx.destination);
canvas繪制頻譜
大頭戲,音樂播放搗鼓搗鼓還是有聲音的,頻譜怎么著,一頭霧水。不著急,慢慢來,首先我們需要數(shù)據(jù),數(shù)據(jù)怎么來:
var bufferLength = analyser.frequencyBinCount,
dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
好,數(shù)據(jù)有了,計(jì)算機(jī)也能懂,怎么畫,先說個(gè)簡單的:
var canvas = document.getElementById('audio_canvas'),
ctx = canvas.getContext("2d"),
c_width = canvas.width,
c_height = canvas.height;
**************
for(var i = 0; i < bufferLength; i++) {
value = dataArray[i];
ctx.fillStyle = '#f99';
ctx.fillRect(i, c_height - value, 1, value);
}
好了,頻譜圖有了,但沒有動(dòng)效,不會(huì)變化,別急,利用requestAnimationFrame,同時(shí)這側(cè)面反應(yīng)了獲取的dataArray數(shù)組的數(shù)值,出來的效果如此這般:

可是我們想,如果把所有的數(shù)值都展現(xiàn)出來,一來太多,二來更耗資源,而且頻率鄰值是相似的,非智者所為,怎么處理呢?數(shù)學(xué)中有學(xué)過采樣頻率的方法,采樣對(duì)于信息信號(hào)來說,是個(gè)常用的方式。根據(jù)畫布長度,美觀起見,讓每一頻占據(jù)一定寬度,各個(gè)頻之間留些空隙,同時(shí)用數(shù)學(xué)邏輯思維換算,計(jì)算出畫布可放的頻數(shù),也就是說畫布上選擇哪幾個(gè)頻率值顯示,取相對(duì)應(yīng)“編號(hào)”的頻率,進(jìn)行繪制。
// 條形的寬度
var bar_width = 10,
bar_gap = 2,
bar_part = bar_width + bar_gap,
bar_num = Math.round(c_width / bar_part);
***************************************
function drawVisual() {
var i = 0, value;
var bufferLength = analyser.frequencyBinCount,
dataArray = new Uint8Array(bufferLength);
// 每段包含的頻譜寬
var array_width = Math.round(bufferLength / bar_num);
analyser.getByteFrequencyData(dataArray);
ctx.clearRect(0,0,c_width,c_height)
for(i; i < bar_num; i++) {
value = dataArray[i * array_width];
ctx.fillStyle = '#f99';
ctx.fillRect(bar_part * i, c_height - value, bar_width, value);
}
animation_id = requestAnimationFrame(drawVisual);
// console.log(animation_id)
}

思考
如此一來,大致效果已經(jīng)實(shí)現(xiàn)。在做的過程中,有一個(gè)問題需要思考: 動(dòng)畫什么時(shí)候停止,也就是說,如何在音樂播放結(jié)束的情況下,頁面頻譜流暢地回歸空白,瀏覽器也不會(huì)繼續(xù)動(dòng)畫,做到“該停止時(shí)就停止”?!緦?shí)踐結(jié)果證明,如果在音樂播放結(jié)束就停止動(dòng)畫或者清空,達(dá)不到想要的效果】

為了美觀及更有趣味性,我們可以加個(gè)緩慢降落的條形;甚者,采取上傳文件的形式,根據(jù)上傳的音樂“舞動(dòng)”自己的音浪,因頻制浪。這里有個(gè)稍難的點(diǎn):已經(jīng)播放一首音樂的時(shí)候,如何做到繼續(xù)上傳,原音樂停止,新音樂播放并出現(xiàn)相應(yīng)的頻譜。


【代碼存在于 github,僅供參考,敬請(qǐng)交流】
參考文章:
https://www.google.com.hk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwj9xpzE2K_SAhUNtJQKHQQMCu4QFggaMAA&url=https%3a%2f%2fdeveloper%2emozilla%2eorg%2fzh-CN%2fdocs%2fWeb%2fAPI%2fFileReader&usg=AFQjCNGz5Veo8Ux5iQ_w_1oFQc3fqNlynA
http://www.cnblogs.com/Wayou/p/html5_audio_api_visualizer.html
https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API
https://forestmist.org/blog/web-audio-api-loops#source