-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBEATLOOP JS
More file actions
98 lines (84 loc) · 2.66 KB
/
BEATLOOP JS
File metadata and controls
98 lines (84 loc) · 2.66 KB
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
const fileUpload = document.getElementById('file-upload');
const pitchRange = document.getElementById('pitch');
const toneRange = document.getElementById('tone');
const volumeRange = document.getElementById('volume');
const muteButton = document.getElementById('mute');
const playButton = document.getElementById('play');
let audioContext;
let audioSource;
let gainNode;
let isPlaying = false;
function loadAudio(file) {
if (audioSource) {
audioSource.stop();
audioSource.disconnect();
audioSource = null;
}
const reader = new FileReader();
reader.onload = function() {
audioContext.decodeAudioData(reader.result, function(buffer) {
audioSource = audioContext.createBufferSource();
audioSource.buffer = buffer;
gainNode = audioContext.createGain();
audioSource.connect(gainNode);
gainNode.connect(audioContext.destination);
audioSource.loop = true;
audioSource.start(0);
isPlaying = true;
playButton.innerText = 'Stop';
});
};
reader.readAsArrayBuffer(file);
}
function init() {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
fileUpload.addEventListener('change', function(event) {
const file = event.target.files[0];
loadAudio(file);
});
pitchRange.addEventListener('input', function() {
if (audioSource) {
audioSource.playbackRate.value = this.value / 100;
}
});
toneRange.addEventListener('input', function() {
if (audioSource) {
const cents = this.value;
const pitchSemitones = cents / 100;
const pitchValue = Math.pow(2, pitchSemitones);
audioSource.detune.value = pitchValue * 100;
}
});
volumeRange.addEventListener('input', function() {
if (gainNode) {
const volume = this.value / 100;
gainNode.gain.setValueAtTime(volume, audioContext.currentTime);
}
});
muteButton.addEventListener('click', function() {
if (gainNode) {
if (gainNode.gain.value === 0) {
const volume = volumeRange.value / 100;
gainNode.gain.setValueAtTime(volume, audioContext.currentTime);
muteButton.innerText = 'Mute';
} else {
gainNode.gain.setValueAtTime(0, audioContext.currentTime);
muteButton.innerText = 'Unmute';
}
}
});
playButton.addEventListener('click', function() {
if (audioSource) {
if (isPlaying) {
audioSource.stop();
isPlaying = false;
playButton.innerText = 'Start';
} else {
audioSource.start(0);
isPlaying = true;
playButton.innerText = 'Stop';
}
}
});
}
init();