react-mic-record
Version:
Record audio from your microphone
111 lines (79 loc) • 3.47 kB
JavaScript
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var Visualizer = function () {
function Visualizer(audioContext, canvasCtx, canvas, width, height, backgroundColor, strokeColor) {
_classCallCheck(this, Visualizer);
this.analyser = audioContext.getAnalyser();
this.canvasCtx = canvasCtx;
this.canvas = canvas;
this.width = width;
this.height = height;
this.backgroundColor = backgroundColor;
this.strokeColor = strokeColor;
this.drawVisual = null;
}
Visualizer.prototype.visualizeSineWave = function visualizeSineWave() {
var _this = this;
this.analyser.fftSize = 2048;
var bufferLength = this.analyser.fftSize;
var dataArray = new Uint8Array(bufferLength);
this.canvasCtx.clearRect(0, 0, this.width, this.height);
var draw = function draw() {
_this.drawVisual = requestAnimationFrame(draw);
_this.analyser.getByteTimeDomainData(dataArray);
_this.canvasCtx.fillStyle = _this.backgroundColor;
_this.canvasCtx.fillRect(0, 0, _this.width, _this.height);
_this.canvasCtx.lineWidth = 2;
_this.canvasCtx.strokeStyle = _this.strokeColor;
_this.canvasCtx.beginPath();
var sliceWidth = _this.width * 1.0 / bufferLength;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = v * _this.height / 2;
if (i === 0) {
_this.canvasCtx.moveTo(x, y);
} else {
_this.canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
_this.canvasCtx.lineTo(_this.canvas.width, _this.canvas.height / 2);
_this.canvasCtx.stroke();
};
draw();
};
Visualizer.prototype.visualizeFrequencyBars = function visualizeFrequencyBars() {
var _this2 = this;
this.analyser.fftSize = 256;
var bufferLength = this.analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
this.canvasCtx.clearRect(0, 0, this.width, this.height);
var draw = function draw() {
_this2.drawVisual = requestAnimationFrame(draw);
_this2.analyser.getByteFrequencyData(dataArray);
_this2.canvasCtx.fillStyle = _this2.backgroundColor;
_this2.canvasCtx.fillRect(0, 0, _this2.width, _this2.height);
var barWidth = _this2.width / bufferLength * 2.5;
var barHeight = void 0;
var x = 0;
for (var i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
var rgb = hexToRgb(_this2.strokeColor);
_this2.canvasCtx.fillStyle = _this2.strokeColor;
_this2.canvasCtx.fillRect(x, _this2.height - barHeight / 2, barWidth, barHeight / 2);
x += barWidth + 1;
}
};
draw();
};
return Visualizer;
}();
export { Visualizer as default };