“滄海一聲唱 滔滔兩岸潮
浮沉隨浪歌舞今朝
蒼天唱 紛紛世上潮
誰負(fù)誰勝出天知曉
江山唱 煙雨遙
濤浪淘盡紅塵俗世幾多嬌
清風(fēng)唱 竟惹寂寥
豪情還剩了一襟晚照
蒼生唱 不再寂寥
豪情仍在癡癡唱唱”
—— 題記峻厚,《滄海一聲唱》
正文
在上文 JS | Web Audio API (上) 你的音譜 中侨把,我們了解到Audio API簡單的音頻知識點(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,震撼摘能,神奇续崖,而對于喜歡的事物,總會(huì)想為我所用团搞,閑話不多說严望,一起看看它是怎么實(shí)現(xiàn)的吧。根據(jù)已有的web audio API知識逻恐,實(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獲取,將請求的返回類型設(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 請求參數(shù), 配置請求類型,文件路徑等
xhr.open('GET', 'audio/music1.mp3');
// 將responseType設(shè)為arraybuffer,二進(jìn)制數(shù)據(jù)
xhr.responseType = "arraybuffer";
// 獲取完成俱济,對音頻進(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ī)仍然不懂,需要對其進(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é)過采樣頻率的方法酥诽,采樣對于信息信號來說鞍泉,是個(gè)常用的方式。根據(jù)畫布長度肮帐,美觀起見咖驮,讓每一頻占據(jù)一定寬度,各個(gè)頻之間留些空隙训枢,同時(shí)用數(shù)學(xué)邏輯思維換算游沿,計(jì)算出畫布可放的頻數(shù),也就是說畫布上選擇哪幾個(gè)頻率值顯示肮砾,取相對應(yīng)“編號”的頻率,進(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台谍,僅供參考,敬請交流】
參考文章:
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