forked from acidsound/band4all
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.js
152 lines (141 loc) · 3.82 KB
/
setup.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
userId = UUID.generate();
console.log("init", userId);
client = new Paho.MQTT.Client(
"mqtt.sheepal.ga",
Number(443),
`band4all_${userId}`
);
AudioContext = window.AudioContext || window.webkitAudioContext;
room = new URLSearchParams(location.search).get("room") || "lobby";
sendMessage = (dstName, msg) => {
console.log(dstName);
const message = Object.assign(
new Paho.MQTT.Message(
JSON.stringify({
id: userId,
...msg,
})
),
{
destinationName: dstName,
}
);
client.send(message);
};
peers = {};
const onConnect = function () {
client.subscribe(`${room}/join`);
client.subscribe(`${room}/leave`);
client.subscribe(`${room}/signal/${userId}`);
sendMessage(`${room}/join`);
};
const onConnectionLost = function (responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:", responseObject.errorMessage);
}
};
/* webRTC datachannel stuff */
onMessageArrived = function (message, topic) {
let parsedMessage;
try {
parsedMessage = JSON.parse(message.payloadString);
} catch (e) {
return;
}
if (parsedMessage.id === userId) {
return;
}
console.log("onMessageArrived", parsedMessage);
({
[`${room}/join`]: ({ id }) =>
createPeerFactory({ peerId: id, initiator: true }),
[`${room}/leave`]: ({ id }) => peers[id]?.destroy() || delete peers[id],
[`${room}/signal/${userId}`]: ({ id, signal }) =>
(peers[id] || createPeerFactory({ peerId: id, initiator: false })).signal(
signal
),
}[message.destinationName](parsedMessage));
};
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
const willMessage = Object.assign(
new Paho.MQTT.Message(JSON.stringify({ id: userId })),
{
destinationName: `${room}/leave`,
qos: 0,
retained: false,
}
);
client.connect({
onSuccess: onConnect,
useSSL: true,
userName: "test",
password: "test",
willMessage,
});
navigator.requestMIDIAccess &&
navigator.requestMIDIAccess().then((ma) =>
Array.from(ma.inputs).forEach(
(input) =>
(input[1].onmidimessage = function ({ data }) {
const [msg, key, val] = data;
if (msg === 144) {
playKey(val / 127.0, key);
}
})
)
);
createPeerFactory = ({ peerId, initiator }) => {
const peer = new SimplePeer({
config: {
iceServers: [
{ urls: "stun:stun.l.google.com:19302" },
{ urls: "stun:global.stun.twilio.com:3478?transport=udp" },
{
urls: "turn:turn.sheepal.ga:3478",
username: "band4all",
credential: "band4all1234",
},
],
},
initiator,
});
peer.on("signal", (signal) => {
console.log("peer:onSignal", signal);
sendMessage(`${room}/signal/${peerId}`, { signal });
});
peer.on("connect", () => {
console.log("peer:establish datachannel");
});
peer.on("data", (data) => {
const msg = data.toString();
if (msg[0] === "@") {
const [prg, key, vel, senderId, timeStamp] = msg.slice(1).split("/");
console.log("latency:", Date.now() - timeStamp);
if (senderId !== userId) {
const programMap = {
drum: () => playDrum(vel, key, false),
piano: () => playKey(vel, key, false),
none: () => {},
};
(programMap[prg] || programMap["none"])();
}
}
});
peer.on("close", () => {
console.log("peer:close peer. peerId:", peerId);
});
peer.on("error", (err) => {
console.log("peer:err:", err);
});
return (peers[peerId] = peer);
};
broadCast = function ({ destination, patch, vel, key }) {
Object.values(peers).forEach((peer) => {
if (peer.connected) {
peer.send(`@${patch}/${key}/${vel}/${userId}/${Date.now()}`);
}
});
};
context = new AudioContext();
console.log("audioContext state", context.state);