Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added audio-in-javascript.md #1956

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added assets/cover/drums.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions snippets/js/s/audio-in-javascript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
---
title: "Adding sound in JavaScript"
type: snippet
language: javascript
tags: [audio,html,javascript]
author: Vivek Kumar
cover: drums
dateModified: 2023-07-01T08:39:26Z
---

The simplest way to add audio to your HTML file is through the use of Javascript's Audio() constructor.To achieve this you can follow the steps below:

- Create an audio object,
- attach the audio object an event.

```html
<body>
<button id="play">Play</button>
<script src="index.js"></script>
</body>
```

```js
var audio=new Audio('./crash.mp3'); // specify audio file-path or and url
const ele=document.querySelector("button");
ele.addEventListener("click",function(){
audio.play();
console.log("audio file")
})
```
Another way to achieve the same is through the use of HTML audio tag.

```html
<body>
<audio id="audio" autopaly loop controls src="./crash.mp3"></audio>
</body>
```
```js
var audio=document.querySelector("#audio");
audio.play();
```
- The audio tag attribute autoplay indicates that when our audio file is called within our Javascript file it will begin playing in the browser automatically.
-Loop indicates that the audio file will loop back to the beginning of the audio clip indefinitely when finished.
-Controls create controls in the browser which allow the user to adjust volume, seeking, and other audio playback features.