-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
63 lines (51 loc) · 1.91 KB
/
main.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
document.addEventListener('DOMContentLoaded', function() {
// Variable to store reference to the currently playing audio
var currentAudio = null;
// Function to play the sound
function playSound(soundFile) {
// If there's an existing audio element, stop and reset it
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
} else {
// Create a new audio element
currentAudio = new Audio();
}
// Set the audio source
currentAudio.src = soundFile;
// Play the audio
currentAudio.play();
}
// Function to stop the currently playing audio
function stopMusic() {
if (currentAudio) {
currentAudio.pause();
currentAudio.currentTime = 0;
// Remove the audio source to prevent any further play
currentAudio.src = "";
// Help with garbage collection by nullifying the reference
currentAudio = null;
}
}
// Get the submit button element
var submitButton = document.getElementById('submit');
// Add event listener for submit button click
submitButton.addEventListener('click', submitForm);
// Function to handle form submission
function submitForm(event) {
// Prevent default form submission
event.preventDefault();
// Get the selected genre
var selectedGenre = document.getElementById('genre').value;
// Check if there's currently playing audio and pause it
if (currentAudio) {
currentAudio.pause();
}
// Play the sound based on the selected genre
playSound(selectedGenre + '.mp3');
}
// Get the stop music button element
var stopButton = document.getElementById('stopbutton');
// Add event listener for stop music button click
stopButton.addEventListener('click', stopMusic);
});