-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio-context.js
81 lines (67 loc) · 1.83 KB
/
audio-context.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
import React from "react";
import PropTypes from "prop-types";
import RComponent from "./component.js";
window.AudioContext = window.AudioContext || window.webkitAudioContext || null;
if (!window.AudioContext) {
throw new Error(
"Could not find AudioContext. This may be because your browser does not support Web Audio."
);
}
/**
* Contains and manages the Web Audio graph.
* All immediate children connect directly to its Destination.
*
* @class RAudioContext (name)
*/
export default class RAudioContext extends React.Component {
constructor(props) {
super(props);
// repository of all nodes in the graph
// keyed by Symbols
this.nodes = new Map();
this._context = new AudioContext(props.options);
if (this.props.onInit) this.props.onInit(this._context);
if (this.props.debug) {
window.RAudioNodeMap = this.nodes;
}
}
componentWillMount() {
this._context.resume();
}
getChildContext() {
return {
audio: this._context,
debug: this.props.debug,
nodes: this.nodes,
};
}
componentWillUnmount() {
this._context.suspend();
}
render() {
const children = React.Children.toArray(this.props.children).map(
(child) => {
if (!RComponent.isPrototypeOf(child.type)) return child;
const audioContextProps = {
destination: () => this._context.destination,
identifier: Symbol(child.type.name),
};
return React.cloneElement(child, audioContextProps);
}
);
if (this.props.debug) {
return (
<div>
<strong>RAudioContext</strong>
<ul>{children}</ul>
</div>
);
}
return children || [];
}
}
RAudioContext.childContextTypes = {
audio: PropTypes.instanceOf(AudioContext),
nodes: PropTypes.instanceOf(Map),
debug: PropTypes.bool,
};