Created
July 4, 2015 05:10
-
-
Save chikoski/24218288290cb5855252 to your computer and use it in GitHub Desktop.
リアルタイムに周波数領域分析をして、それぞれの音の強さを可視化するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// アニメーションの各フレームを描画する関数 | |
function draw(){ | |
// 全画面を黒で塗りつぶし、リセット | |
ctx.fillStyle = "rgb(0, 0, 0)"; | |
ctx.fillRect(0, 0, canvas.width, canvas.height); | |
var data = getData(); //その時点での曲の解析結果を取得 | |
var i = 0; | |
var offset = 5; | |
var width = (canvas.width - offset * (data.length + 1)) / data.length; | |
var x = offset; | |
ctx.fillStyle = "rgb(255, 255, 255)"; | |
// 解析結果を棒グラフで表示 | |
while(i < data.length){ | |
var h = (data[i]) / 255.0 * canvas.height; | |
ctx.fillRect(x, canvas.height - h, width, h); | |
x = x + width + offset; | |
i = i + 1; | |
} | |
} | |
// 音声を解析するオブジェクトを作成する関数 | |
// http://curtaincall.weblike.jp/portfolio-web-sounder/webaudioapi-visualization/draw-wave に | |
// 解説あり | |
function createAnalyser(){ | |
var player = document.querySelector("audio"); | |
var audioContext = new AudioContext(); | |
var source = audioContext.createMediaElementSource(player); | |
var analyser = audioContext.createAnalyser(); | |
source.connect(audioContext.destination); | |
analyser.fftSize = 256; | |
analyser.minDecibels = -140; | |
analyser.maxDecibels = -10; | |
source.connect(analyser); | |
return analyser; | |
} | |
// 解析結果を配列で返す関数 | |
function getData(){ | |
// var data = new Float32Array(analyser.frequencyBinCount); | |
var data = new Uint8Array(analyser.frequencyBinCount); | |
analyser.getByteFrequencyData(data); | |
return data; | |
} | |
// アニメーションをする関数 | |
// requestAnimationFrame については | |
// http://liginc.co.jp/web/js/130758 に解説があります | |
function update(){ | |
draw(); | |
requestAnimationFrame(update); | |
} | |
// キャンバス | |
var canvas = document.querySelector("canvas"); | |
var ctx = canvas.getContext("2d"); | |
// 音声解析オブジェクトを作成 | |
var analyser = createAnalyser(); | |
// アニメーション開始 | |
update(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>sample audio player</title> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<audio controls preload src="01.mp3"></audio><br> | |
<canvas width="800" height="600"></canvas> | |
<script src="app.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment