-
Notifications
You must be signed in to change notification settings - Fork 2
/
x-play.html
136 lines (118 loc) · 3.27 KB
/
x-play.html
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
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<dom-module id="x-play">
<template>
<style>
#play {
display: inline;
}
#stop {
display: none;
}
</style>
<button id="play" on-click="__handlePlayClick">Play</button>
<button id="stop" on-click="__handleStopClick">Stop</button>
</template>
<script src="./src/js/buffer.js"></script>
<script src="./src/js/player.js"></script>
<script>
/**
* `x-play`
*
*
* @customElement
* @polymer
* @demo demo/index.html
*/
class XPlay extends Polymer.Element {
static get is() { return 'x-play'; }
static get properties() {
return {
formattedMelody: {
computed: 'melodyFormatter(melody)'
},
melody: {
type: String
},
sound: {
type: String,
value: 'piano'
},
repeat: {
type: Number,
value: 1
},
tempo: {
type: Number,
value: 100
}
};
}
melodyFormatter(melody) {
return melody.replace(/\||\r|\n|\r\n/g, '')
.trim()
.split(/\s+/);
}
connectedCallback() {
super.connectedCallback();
}
__handlePlayClick() {
this.__toggleButton();
this.__play();
}
__handleStopClick() {
this.__stop();
}
__toggleButton() {
if (this.$.play.style.display === 'none') {
this.$.play.style.display = 'inline';
this.$.stop.style.display = 'none';
} else {
this.$.play.style.display = 'none';
this.$.stop.style.display = 'inline';
}
}
__createContext() {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
return new AudioContext();
}
__play() {
const context = this.__createContext();
this.player = new Player({
melody: this.formattedMelody,
sound: this.sound,
repeat: this.repeat,
tempo: this.tempo
}, context);
try {
this.player.validate();
} catch(e) {
console.error(e);
return;
}
this.bufferLoader = new BufferLoader(context, this.player.props.sounds, (bufferList) => {
const bpm = 60 / this.player.props.tempo;
const sound = this.player.props.sound;
let code, time, startTime;
time = startTime = context.currentTime;
for (let i = 0, iMax = this.player.props.repeat; i < iMax; i++) {
for (let j = 0, jMax = this.player.props.melody.length; j < jMax; j++) {
time = startTime + (j * bpm);
code = this.player.props.melody[j];
if (this.player.props.rests.indexOf(code) === -1) {
this.player.play(bufferList[sound], time, bpm, code);
}
}
startTime = time + bpm;
}
});
this.bufferLoader.load();
}
__stop() {
this.player.stop(() => {
this.__toggleButton();
});
}
}
window.customElements.define(XPlay.is, XPlay);
</script>
</dom-module>