“滄海一聲唱 滔滔兩岸潮
浮沉隨浪歌舞今朝
蒼天唱 紛紛世上潮
誰負誰勝出天知曉
江山唱 煙雨遙
濤浪淘盡紅塵俗世幾多嬌
清風唱 竟惹寂寥
豪情還剩了一襟晚照
蒼生唱 不再寂寥
豪情仍在癡癡唱唱”
—— 題記,《滄海一聲唱》
正文
在上文 JS | Web Audio API (上) 你的音譜 中,我們了解到Audio API簡單的音頻知識點,重在理論,今天搞點有趣的試驗,偏重實踐。大家知道,光有光譜,電磁波有頻譜,音樂呢?當然也有自己的譜。想奧斯特實驗揭示電流周圍存在磁場,分散的鐵屑顯現磁鐵的磁場分布,那音樂如何看到自身的頻率,所以,本文的主題來了,音頻可視化,讓你的音樂浪起來。先附上效果圖,接下來會主要圍繞效果例子出發:
這種音波似的效果,我們可能會在音樂室或音樂人或音樂播放器那兒看到,并不少見,當第一次發現可以實現時,ohMyGod,震撼,神奇,而對于喜歡的事物,總會想為我所用,閑話不多說,一起看看它是怎么實現的吧。根據已有的web audio API知識,實踐音頻可視化,自我總結,步驟大致分為以下幾步:
- 創建音頻環境
- 獲取音頻,創建buffer節點
- 解碼音頻,分析音頻
- 連接音頻輸入輸出
- canvas繪制頻譜
- 連接播放
創建音頻環境AudioContext
音頻環境是所有音效操作的前提,好比canvas的畫布,先有個做畫之地,再來筆墨橫姿
// 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);
}
獲取音頻,創建buffer節點
首先獲取音頻,也就是說拿到這個素材輸入之后,我們可以趕制加工,這里通過XMLHttpRequest獲取,將請求的返回類型設為“arraybuffer”,方便音頻數據處理;另外,創建音頻節點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 請求參數, 配置請求類型,文件路徑等
xhr.open('GET', 'audio/music1.mp3');
// 將responseType設為arraybuffer,二進制數據
xhr.responseType = "arraybuffer";
// 獲取完成,對音頻進一步操作,解碼
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();
……
}
解碼音頻,分析音頻
好的,現在我們拿到了音樂,但計算機仍然不懂,需要對其進行解碼decodeAudioData。
一看到解碼后的數據,我們不能讓計算機“啪啪啪”就來吧,觀個全局,做個自我分析,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();
}
連接音頻輸入輸出
必經之路,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繪制頻譜
大頭戲,音樂播放搗鼓搗鼓還是有聲音的,頻譜怎么著,一頭霧水。不著急,慢慢來,首先我們需要數據,數據怎么來:
var bufferLength = analyser.frequencyBinCount,
dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
好,數據有了,計算機也能懂,怎么畫,先說個簡單的:
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);
}
好了,頻譜圖有了,但沒有動效,不會變化,別急,利用requestAnimationFrame,同時這側面反應了獲取的dataArray數組的數值,出來的效果如此這般:
可是我們想,如果把所有的數值都展現出來,一來太多,二來更耗資源,而且頻率鄰值是相似的,非智者所為,怎么處理呢?數學中有學過采樣頻率的方法,采樣對于信息信號來說,是個常用的方式。根據畫布長度,美觀起見,讓每一頻占據一定寬度,各個頻之間留些空隙,同時用數學邏輯思維換算,計算出畫布可放的頻數,也就是說畫布上選擇哪幾個頻率值顯示,取相對應“編號”的頻率,進行繪制。
// 條形的寬度
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)
}
思考
如此一來,大致效果已經實現。在做的過程中,有一個問題需要思考: 動畫什么時候停止,也就是說,如何在音樂播放結束的情況下,頁面頻譜流暢地回歸空白,瀏覽器也不會繼續動畫,做到“該停止時就停止”。【實踐結果證明,如果在音樂播放結束就停止動畫或者清空,達不到想要的效果】
為了美觀及更有趣味性,我們可以加個緩慢降落的條形;甚者,采取上傳文件的形式,根據上傳的音樂“舞動”自己的音浪,因頻制浪。這里有個稍難的點:已經播放一首音樂的時候,如何做到繼續上傳,原音樂停止,新音樂播放并出現相應的頻譜。
【代碼存在于 github,僅供參考,敬請交流】
參考文章:
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