Javascript Audio Play on click
Try the below code snippet
<!doctype html>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio>
</body>
</html>
How to play audio?
If you don't want to mess with HTML elements:
var audio = new Audio('audio_file.mp3');
audio.play();
function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>
How to play audio when a button is pressed?
This will work best acc. to your use case.
const btn = document.getElementById("btn");
btn.onclick = () => {
// Here you will add path to local file you have
const audio = new Audio(
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
);
audio.play();
};
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="btn">Play Sound</button>
</div>
<script src="src/index.js"></script>
</body>
</html>
How to play sound on click without waiting for the previous sound to finish playing?
Use the currentTime
property, and take the <audio>
tag outside the <button>
var audio = document.getElementById("audio");
function playSound() { audio.currentTime = 0; audio.play();}
<button onclick="playSound()">Play!</button><audio id="audio" src="https://www.kozco.com/tech/piano2-CoolEdit.mp3"></audio>
Buttons that play audio files when clicked on
JavaScript has audio play()
and pause()
methods we can use to reproduce this behavior. I built the below example using those two methods and built a system of functional operations around them which will allow you to get buttons by media node, get the media file associated with a button node, and play/pause/stop media files effortlessly.
Check it out:
const isPlaying = media => !media.paused;
const play = media => (media.play(), getMediaGroupsByMedia(media).forEach(mgroup => mgroup.dataset.mediaState = "playing"));
const pause = media => (media.pause(), getMediaGroupsByMedia(media).forEach(mgroup => mgroup.dataset.mediaState = "paused"));
const stop = media => (media.pause(), media.currentTime = 0, getMediaGroupsByMedia(media).forEach(mgroup => mgroup.dataset.mediaState = "stopped"));
const allMedia = Array.from(document.querySelectorAll('audio, video'));
const allControls = Array.from(document.querySelectorAll('.media-control'));
const allMediaGroups = Array.from(document.querySelectorAll('.media-group'));
const getMediaByControl = control => allMedia.find(media => media.matches(control.dataset?.target));
const getControlsByMedia = media => allControls.filter(control => document.querySelector(control.dataset?.target) === media);
const getMediaGroupByControl = control => control.closest('.media-group');
const getMediaGroupsByMedia = media => getControlsByMedia(media).map(control => getMediaGroupByControl(control));
const stopAllMedia = () => allMedia.forEach(media => stop(media));
document.addEventListener('click', e => {
if (e.target && allControls.includes(e.target)) {
const control = e.target;
const media = document.querySelector(control.dataset.target);
if (isPlaying(media)) { stop(media); }
else { stopAllMedia(); play(media); }
}
});
document.addEventListener('ended', e => {
if (e.target && allMedia.includes(e.target)) {
const media = e.target;
stop(media);
}
});
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap');
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: 'Noto Sans JP', sans-serif;
}
h1 {
margin: 0 0 10px;
}
.media-group + .media-group {
margin-top: 10px;
}
.media-group .media-control {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
background-color: #546e7a;
border: none;
border-radius: 7px;
color: rgba(255, 255, 255, 0.875);
overflow: hidden;
cursor: pointer;
}
.media-group .media-control::after {
content: '▶';
transform: rotate(0deg);
transition: transform 0.15s ease-out;
pointer-events: none;
}
.media-group[data-media-state="playing"] .media-control {
background-color: #4caf50;
}
.media-group[data-media-state="playing"] .media-control::after {
transform: rotate(90deg);
}
<h1>Audio Sample Previews</h1>
<div class="media-group" data-media-state="stopped">
<span>Audio #1</span>
<button class="media-control" data-target="#audio1"></button>
</div>
<div class="media-group" data-media-state="stopped">
<span>Audio #2</span>
<button class="media-control" data-target="#audio2"></button>
</div>
<audio id="audio1">
<source src="https://assets.codepen.io/1580009/sample1.ogg" type="audio/ogg">
<source src="https://assets.codepen.io/1580009/sample1.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="audio2">
<source src="https://assets.codepen.io/1580009/sample2.ogg" type="audio/ogg">
<source src="https://assets.codepen.io/1580009/sample2.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Related Topics
Check If Object Is a Jquery Object
Eslint Parsing Error: Unexpected Token
How to Do a Deep Comparison Between 2 Objects with Lodash
How to Break Nested Loops in JavaScript
Access Denied to Jquery Script on Ie
Dc.Js - How to Create a Row Chart from Multiple Columns
What Does $.When.Apply($, Somearray) Do
What Is {This.Props.Children} and When You Should Use It
Using Async/Await Inside a React Functional Component
How to Sort an Array of Objects Based on the Ordering of Another Array
Node.Js Tail-Call Optimization: Possible or Not
How to Create a Web Worker from a String
Referenceerror: Fetch Is Not Defined
JavaScript Accessing Inner Dom of Svg
Capture Value Out of Query String with Regex
JavaScript Getelementbyid() Not Working
Indirect Function Call in JavaScript
Facebook How to Check If User Has Liked Page and Show Content