Home >Web Front-end >JS Tutorial >How Can I Play Audio in My JavaScript HTML5 Games?

How Can I Play Audio in My JavaScript HTML5 Games?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 08:38:10491browse

How Can I Play Audio in My JavaScript HTML5 Games?

Playing Audio in JavaScript Games

In developing HTML5 games with JavaScript, adding audio can enhance the user experience. This article provides guidance on how to play game audio using JavaScript.

Playing Audio Through HTML5 Audio Element

For seamless audio playback, consider using the

<audio src="audio_file.mp3" controls></audio>

This creates an HTML audio element with playback controls. Accessing the element in JavaScript allows you to manipulate playback properties:

var audioElement = document.querySelector("audio");
audioElement.play();

Playing Audio Without HTML Elements

If manipulating HTML is undesirable, use the following JavaScript-only method:

var audio = new Audio("audio_file.mp3");
audio.play();

This creates a new Audio object and initiates playback.

Callback Handling

For extended control, utilize audio event listeners:

// On load:
audio.addEventListener("canplaythrough", function() {
  console.log("Audio is ready to play");
});

// On playback completion:
audio.addEventListener("ended", function() {
  console.log("Audio playback completed");
});

The above is the detailed content of How Can I Play Audio in My JavaScript HTML5 Games?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn