Good afternoon! I am developing a game in JavaScript, in fact rather creating my own version of a very classic one that already exists, and to make the game a little more dynamic and fun I wanted to add Audio, however I realize that when trying to play the audio, it doesn't work! As an important note, one of those audios is in the html, the rest will be in javascript:
Html code:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="styles.css">
<script type = "module" src="scripts/script.js"></script>
<title>Tetris</title>
</head>
<body>
<div id="points" class="points">0</div>
<canvas id="canvas" width = "390" height="720"></canvas>
<audio src="sounds/tetris_song.mp3" type="audio/mpeg" preload = "auto" autoplay loop></audio>
</body>
</html>
That is the only audio that I want to be repeated and heard as soon as the page loads, the rest of the audios, my intention was to load them in Javascript, in fact I didn't even want the html audio to work, however, when I commented absolutely all the code in javascript to "Try to play an audio that I don't want to be repeated" and reload the local server, I realized that the audio works correctly in html!
However, and of course, to be able to know what happens and that and see how it can be solved, here is the code that I tried to use in javascript to load and play a single audio (I will only show the audio code), (my intention was have multiple encapsulations):
window.onload = ()=>{
const songs = {
//Aquí tendre varios audios, sin embargo para experimentar de momento solo tengo este:
rotation_moving: new Audio("sounds/rotation and moving.wav")
}
const promesa = new Promise((resolve,reject)=>{
songs.rotation_moving.onload = ()=>{
resolve();
}
});
promesa.then(()=>{
console.log(songs.rotation_moving);
songs.rotation_moving.play();//NO SUENA
}).catch(()=>{
console.log("Ha habido un error!");/*No muestra que allá habido un error,
por lo cual probablemente llego al then, sin embargo, aun así, no suena...*/
});
}
Note that I'm not using xampp's localhost, I'm using nodejs's http-server.
The other thing is that when I create audios in javascript, the audio that worked correctly in HTML automatically stops working and doesn't sound or anything, of course the audios in javascript don't sound either.
The problem is that your promise isn't resolving, so it doesn't make it to the
then
. Within the promise, only one is being definedcallback
, but it is not executed.Another important thing is that when you build the object
Audio
the attributepreload
defaults toauto
, so it starts downloading the audio file before you define the response to the eventload
.Next, I leave you a simple example of how to play an audio.
This is a modification to your code to make it run correctly.