Dome在這 因爲兼容性的問題還沒解決!css
某天在觀看TED演講Aparna Rao High tech Art with a sense of humor的時候看到裏面的一個項目叫作pygmies,中文名叫俾格米人(圖中的小黑人)。他們都很膽小,只要有聲音就會被嚇到躲到板子後面。html
該項目的實物是由來自印度的團隊製做的。測試中,俾格米人表現得唯妙唯肖,就像是一羣好奇而又膽小的小動物。十分可愛!web
因而我想用web技術彷佛也能達到一樣的效果。只須要瀏覽器調用麥克風,獲取數據,做用於svg元素(固然這是最初的簡單想法)。數組
做圖工具,Mac平臺sketch 瀏覽器
html部分bash
// 主要是svg代碼,量比較大,請在源碼中查看
複製代碼
css部分svg
// 主要是基本的定位代碼,請在源碼中查看
複製代碼
js部分工具
"use strict";
var ctx, analyser, frequencies, getByteFrequencyDataAverage, draw;
// 兼容性
window.AudioContext = window.AudioContext || window.webkitAudioContext;
// 獲取音頻上下文
ctx = new window.AudioContext();
// 用戶獲取stream當中的時間、頻率信息
analyser = ctx.createAnalyser();
frequencies = new Uint8Array(analyser.frequencyBinCount);
getByteFrequencyDataAverage = function() {
// 將當前頻域數據拷貝進數組
analyser.getByteFrequencyData(frequencies);
// 求得頻域的平均值
return (
frequencies.reduce(function(previous, current) {
return previous + current;
}) / analyser.frequencyBinCount
);
};
// 返回 Promise 對象
navigator.mediaDevices
.getUserMedia({ audio: true })
.then(function(stream) {
// window.hackForMozzila = stream;
ctx
.createMediaStreamSource(stream)
// 鏈接到AnalyserNode
.connect(analyser);
})
.catch(function(err) {
console.log(err.message);
});
var pygmies = [];
for (let i = 0; i < 10; i++) {
pygmies.push(document.getElementById(`pygmie-${i + 1}`));
}
// 改變小人的位置
(draw = function() {
var moveValue = getByteFrequencyDataAverage() * 10;
if (moveValue >= 35) {
moveValue = 35;
}
pygmies[0].style.transform = `translate(51.000000px, ${moveValue}px)`;
console.log(getByteFrequencyDataAverage());
pygmies[1].style.transform = `translate(89.000000px, ${0.0 + moveValue}px)`;
pygmies[2].style.transform = `translate(149.000000px, ${0.0 + moveValue}px)`;
pygmies[3].style.transform = `translate(218.000000px, ${0.0 + moveValue}px)`;
pygmies[4].style.transform = `translate(286.500000px, 51.000000px) rotate(90.000000deg) translate(-286.500000px, -51.000000px) translate(275.000000px, ${34.0 +
moveValue}px)`;
pygmies[5].style.transform = `translate(286.500000px, 152.000000px) rotate(90.000000deg) translate(-286.500000px, -152.000000px) translate(275.000000px, ${135.5 +
moveValue}px)`;
pygmies[6].style.transform = `translate(286.500000px, 196.5000000px) rotate(90.000000deg) translate(-286.500000px, -196.500000px) translate(275.000000px, ${179.5 +
moveValue}px)`;
pygmies[7].style.transform = `translate(17.500000px, 173.500000px) rotate(-90.000000deg) translate(-17.00000px, -173.500000px) translate(5.500000px, ${156.5 +
moveValue}px)`;
pygmies[8].style.transform = `translate(17.000000px, 106.500000px) rotate(-90.000000deg) translate(-17.00000px, -106.500000px) translate(5.500000px, ${89.5 +
moveValue}px)`;
pygmies[9].style.transform = `translate(17.00000px, 252.500000px) rotate(-90.000000deg) translate(-17.00000px, -252.500000px) translate(5.500000px, ${235.5 +
moveValue}px)`;
requestAnimationFrame(draw);
})();
複製代碼
代碼主要是作了兩件事:性能
只不過須要不斷的循環,來獲取最新的信息。測試