-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAudioMeter.react.js
101 lines (86 loc) · 3.15 KB
/
AudioMeter.react.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Polyfill: mediaDevices.
// Not work on Desktop Safari, IE.
// Not work on Mobile browsers.
navigator.mediaDevices = function() {
if (navigator.mediaDevices) {
return navigator.mediaDevices;
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
return {
getUserMedia: function (c) {
return new Promise(function(y, n) {
navigator.getUserMedia.call(navigator, c, y, n);
}
);
}
}
}
}();
if (!navigator.mediaDevices) {
alert("mediaDevices() not supported.");
throw new Error("mediaDevices() not supported.")
}
// Polyfill: AudioContext.
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
var AudioMeter = React.createClass({
getInitialState: function() {
return {
volume: 0,
debug: false
};
},
componentDidMount: function () {
// Processing.
var process = function (event) {
var buf = event.inputBuffer.getChannelData(0);
var sum = 0;
var x;
for (var i = 0; i < buf.length; i++) {
x = buf[i];
sum += x * x;
}
var rms = Math.sqrt(sum / buf.length);
this.setState({
volume: Math.max(rms, this.state.volume * this.averaging)
});
//console.log('Volume: ' + this.state.volume);
this.canvasCtx.clearRect(0, 0, this.canvasCtx.canvas.width, this.canvasCtx.canvas.height);
this.canvasCtx.fillRect(0, this.canvasCtx.canvas.height * (1 - this.state.volume), this.canvasCtx.canvas.width, this.canvasCtx.canvas.height);
}.bind(this);
// Init processing.
navigator.mediaDevices.getUserMedia(
{
audio: true
}
).then(function(stream) {
var audioCtx = new AudioContext();
var source = audioCtx.createMediaStreamSource(stream);
var processor = audioCtx.createScriptProcessor(256);
this.averaging = 0.95;
this.canvasCtx = this.refs.canvas.getContext('2d');
this.canvasCtx.fillStyle = '#00FF48';
processor.onaudioprocess = process;
processor.connect(audioCtx.destination);
source.connect(processor);
}.bind(this)
).catch(function(err){
console.log('Error occurred while initalizing audio input: ' + err.toString());
});
},
toggleDebug: function() {
this.setState({
debug: !this.state.debug
});
},
render: function() {
return (
<div>
<canvas ref="canvas" width="30" height="78"></canvas>
<p></p>
<button onClick={this.toggleDebug}>Debug</button>
{ this.state.debug ? <p>Volume: {this.state.volume} </p>: null}
</div>
);
}
});