javascript onload play audio file - javascript

I have an audio file with a button when I click on it the audio play and when I click again the audio pause I also want when the page is load the audio play directly without clicking on the button
I tried autoplay in the html but it didn't work
I tried allow="autoplay" also it didn't work
I tried window.addEventListener('load') also it didn't work
I read that I should use muted but also it didn't work
I'm using chrome and firefox
How can I make this audio work on refresh or on load for the page and when i click in the button the audio will be pause it and when I click again the audio will be played
I searched on stack overflow but nothing solve my problem
let audio = document.querySelector('.music audio');
let audioBtn = document.querySelector('.music .musicBtn i');
audio.volume = 0.2;
window.addEventListener("load", () => {
audio.play();
});
audioBtn.addEventListener("click", () => {
if (audio.paused) {
audio.play();
audioBtn.classList.add('fa-volume-up');
audioBtn.classList.remove('fa-volume-mute');
} else {
audio.pause();
audioBtn.classList.add('fa-volume-mute');
audioBtn.classList.remove('fa-volume-up');
}
});
.musicBtn {
background: transparent;
padding: 1.5rem 2rem;
font-size: 3rem;
border: none;
cursor: pointer;
}
<div class="music">
<audio id="audio" style="display:none;" src="music/music.mp3" allow="autoplay" controls autoplay loop></audio>
<button class="musicBtn"><i class="fas "></i></button>
</div>
<script src="https://kit.fontawesome.com/9e5ba2e3f5.js" crossorigin="anonymous"></script>

You can not, as browsers only allow playing sounds as a consequence of user-interaction. You could try to hijack any click or mouse movement to enable the plaining of sound, but there is no way to really do it on load alone.
https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

You can try manual interaction by clicking on the play button on DOM load so that the audio plays,
if (document.readyState === 'complete') {
document.getElementById('#playButton').click();
}

Related

change play/pause button when audio is played (inner html)

I'm coding a playlist.
I would like to create a button that would pause/play my audios. One button that would work for all my audios no matter which one is currently playing.
For now, I have a button that can pause the audio playing, but I can't manage to make a button that resumes the audio where it stopped.
On click on title, the audio starts playing.
On click on the button, I'd like to pause or resume the audio playing, and to change the text from Pause to Play and vis-versa.
If you click on a title again, I'd like the audio to play from beginnig.
Here is the html :
<div class="audio" onclick=
"playAudio('algebrasuicide_fathersbythedoor.wav')">algebra suicide father by the door
</div>
<div class="audio"onclick=
"playAudio('algebrasuicide_inbedwithboys.wav')">
algebra suicide in bed with boys
</div>
<div class="audio"onclick=
"playAudio('aprilmagazine_parade.wav')">
april magazine parade
</div>
<button onclick="pauseAudio()">
pause
</button>
Here is the js :
let audio;
function stopAudio() {
if (audio && !audio.paused) {
audio.pause();
audio.currentTime = 0;
}
}
function playAudio(src) {
stopAudio();
audio = new Audio();
audio.src = src;
audio.play();
}
function pauseAudio(){
audio.pause();
}
From what I understand I may need to change the inner html or to add a player but I tried a lot of codes from SO and can't manage to find how to make it work.
I hope you can help me ! It's probably simple but I'm very novice.
Thank you :)

Playing multiple sound files with one button

I was wondering if it's possible to play multiple audio files with just one button? From there, I want the user to be able to mute each audio file, so everything runs simultaneously.
I don't have much experience with backend web development, so a little push in the right direction would be greatly appreciated!
You can start playing of multiple audios on the click of a single button simply by calling the play function on each audio you want to start.
This snippet has a couple of audio elements. On button click they each have their play function called.
Note that each one has the controls attribute so the user can pause them individually. (It also has loop on each just for this demo as each audio is quite short).
function playAll() {
document.querySelector('.container').classList.add('playing');
const audios = document.querySelectorAll('audio');
audios.forEach(audio => {
audio.play();
});
}
.container {
display: none;
}
.container.playing {
display: block;
}
<button onclick="playAll();">Play them all</button>
<div class="container">
<h2>Horse
</h2> <audio src="https://www.w3schools.com/html/horse.mp3" controls loop></audio>
<h2>Placeholder</h2> <audio src="https://ia903002.us.archive.org/18/items/placeholder/placeholder.mp3" controls loop></audio>
</div>

allow one audio player to play at a time

I have multiple audio players, each with a play and stop button, on one page. The only issue I have is when you click one play button, and then another, they play on top of one another. Can someone help me with the code I would need to stop whatever song is playing when another play button is clicked. Here's are my code. Thank you
function disableButton(btn) {
document.getElementById(btn.id).disabled = true;
}
function change() {
var image = document.getElementById('image');
image.src = "https://lms.testing.com/je_audio/html/button2.png"
}
#btn1 {
border: none;
padding: 0;
background: none;
}
<audio id="player">
<source src="https://lms.testing.com/els_audio/PATAudios/Q1.mp3" type="audio/mpeg">
Your browser has not support the audio element.
</audio>
<div>
<button id="btn1" onclick="document.getElementById('player').play('play'); disableButton(this)"><img src="https://lms.testing.com/je_audio/html/button1.png" width="95" height="28" alt="button" id="image" onclick="change();"></button>
</div>
Listen for the play event on all the <audio> elements.
Whenever one audio element starts playing, pause all the other ones.
// Get all <audio> elements.
const audios = document.querySelectorAll('audio');
// Pause all <audio> elements except for the one that started playing.
function pauseOtherAudios({ target }) {
for (const audio of audios) {
if (audio !== target) {
audio.pause();
}
}
}
// Listen for the 'play' event on all the <audio> elements.
for (const audio of audios) {
audio.addEventListener('play', pauseOtherAudios);
}
What you have to do is for all the elements first to stop the audio that was previously running audio and then change their images back to play, and try to play the audio for the current media button you are using. Using Class to detect all the Elements using
document.querySelectorAll('.playerButton')
this will help you find all the player button and similarly give a class like AudioFile to that audio that you are using and use the stop() function to stop the audio and then start the audio for the current button clicked using this function.
I hope this will help you, in executing the functionality you are trying to achieve.
you can use the below-given function as an example on how to stop the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
stopAudio(audio)

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

I'm getting the error message..
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
..when trying to play video on desktop using Chrome version 66.
I did find an ad that began playback automatically on a website however using the following HTML:
<video
title="Advertisement"
webkit-playsinline="true"
playsinline="true"
style="background-color: rgb(0, 0, 0); position: absolute; width: 640px; height: 360px;"
src="http://ds.serving-sys.com/BurstingRes/Site-2500/Type-16/1ff26f6a-aa27-4b30-a264-df2173c79623.mp4"
autoplay=""></video>
So is by-passing Chrome v66's autoplay blocker really as easy as just adding the webkit-playsinline="true", playsinline="true", and autoplay="" attributes to the <video> element? Are there any negative consequences to this?
To make the autoplay on html 5 elements work after the chrome 66 update you just need to add the muted property to the video element.
So your current video HTML
<video
title="Advertisement"
webkit-playsinline="true"
playsinline="true"
style="background-color: rgb(0, 0, 0); position: absolute; width: 640px; height: 360px;"
src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
autoplay=""></video>
Just needs muted="muted"
<video
title="Advertisement"
style="background-color: rgb(0, 0, 0); position: absolute; width: 640px; height: 360px;"
src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
autoplay="true"
muted="muted"></video>
I believe the chrome 66 update is trying to stop tabs creating random noise on the users tabs. That's why the muted property make the autoplay work again.
For me (in Angular project) this code helped:
In HTML you should add autoplay muted
In JS/TS
playVideo() {
const media = this.videoplayer.nativeElement;
media.muted = true; // without this line it's not working although I have "muted" in HTML
media.play();
}
Try to use mousemove event listener
var audio = document.createElement("AUDIO")
document.body.appendChild(audio);
audio.src = "./audio/rain.m4a"
document.body.addEventListener("mousemove", function () {
audio.play()
})
The best solution i found out is to mute the video
HTML
<video loop muted autoplay id="videomain">
<source src="videoname.mp4" type="video/mp4">
</video>
Answering the question at hand...
No it's not enough to have these attributes, to be able to autoplay a media with audio you need to have an user-gesture registered on your document.
But, this limitation is very weak: if you did receive this user-gesture on the parent document, and your video got loaded from an iframe, then you could play it...
So take for instance this fiddle, which is only
<video src="myvidwithsound.webm" autoplay=""></video>
At first load, and if you don't click anywhere, it will not run, because we don't have any event registered yet.
But once you click the "Run" button, then the parent document (jsfiddle.net) did receive an user-gesture, and now the video plays, even though it is technically loaded in a different document.
But the following snippet, since it requires you to actually click the Run code snippet button, will autoplay.
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" autoplay=""></video>
This means that your ad was probably able to play because you did provide an user-gesture to the main page.
Now, note that Safari and Mobile Chrome have stricter rules than that, and will require you to actually trigger at least once the play() method programmatically on the <video> or <audio> element from the user-event handler itself.
btn.onclick = e => {
// mark our MediaElement as user-approved
vid.play().then(()=>vid.pause());
// now we can do whatever we want at any time with this MediaElement
setTimeout(()=> vid.play(), 3000);
};
<button id="btn">play in 3s</button>
<video
src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm" id="vid"></video>
And if you don't need the audio, then simply don't attach it to your media, a video with only a video track is also allowed to autoplay, and will reduce your user's bandwidth usage.
Extend the DOM Element, Handle the Error, and Degrade Gracefully
Below I use the prototype function to wrap the native DOM play function, grab its promise, and then degrade to a play button if the browser throws an exception. This extension addresses the shortcoming of the browser and is plug-n-play in any page with knowledge of the target element(s).
// JavaScript
// Wrap the native DOM audio element play function and handle any autoplay errors
Audio.prototype.play = (function(play) {
return function () {
var audio = this,
args = arguments,
promise = play.apply(audio, args);
if (promise !== undefined) {
promise.catch(_ => {
// Autoplay was prevented. This is optional, but add a button to start playing.
var el = document.createElement("button");
el.innerHTML = "Play";
el.addEventListener("click", function(){play.apply(audio, args);});
this.parentNode.insertBefore(el, this.nextSibling)
});
}
};
})(Audio.prototype.play);
// Try automatically playing our audio via script. This would normally trigger and error.
document.getElementById('MyAudioElement').play()
<!-- HTML -->
<audio id="MyAudioElement" autoplay>
<source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
I got this error
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
And here's what I did in my Angular Project
Key Point: Don't ever assume a video will play, and don't show a pause button when the video is not actually playing.
You should always look at the Promise returned by the play function to see if it was rejected:
ngOnInit(): void{
this.ensureVideoPlays();
}
private ensureVideoPlays(): void{
const video = document.querySelector("video");
if(!video) return;
const promise = video.play();
if(promise !== undefined){
promise.then(() => {
// Autoplay started
}).catch(error => {
// Autoplay was prevented.
video.muted = true;
video.play();
});
}
}
Source: Autoplay policy
In my case, I had to do this
// Initialization in the dom
// Consider the muted attribute
<audio id="notification" src="path/to/sound.mp3" muted></audio>
// in the js code unmute the audio once the event happened
document.getElementById('notification').muted = false;
document.getElementById('notification').play();
According to the new browser policy, the user must interact with DOM first before playing the Audio element.
If you want to play the media on page load then you can simply add autoplay property to audio element in HTML like this
<video id="video" src="./music.mp4" autoplay>
or if you don't want to do autoplay then you can handle this using Javascript. Since the autoplay property is set to true, media will be played, we can simply mute the media.
document.getElementById('video').autoplay = true;
document.getElementById('video').muted = true;
Imp: Now Whenever you play the media don't forget to turn the muted property to false. Like this
document.getElementById('video').muted = false;
document.getElementById('video').play();
Or you can also show a simple popup where the user will click the allow button in the modal. So he interacts with DOM first, then you don't need anything to do
I had a similar problem, I need to play the video without muting it. The way i did this, wait for a second then triggered the event by button. Here is my code
if (playVideo == '1') {
setTimeout(function() {
$("#watch_video_btn").trigger('click');
}, 1000);
}
Chrome needs a user interaction for the video to be autoplayed or played via js (video.play()).
But the interaction can be of any kind, in any moment.
If you just click random on the page, the video will autoplay.
I resolved then, adding a button (only on chrome browsers) that says "enable video autoplay". The button does nothing, but just clicking it, is the required user interaction for any further video.
I changed my UI to have the user press a button to load the website (and when the website loads after they click the button, the audio plays)
Since they interact with the DOM, then the audio plays!!!
In my case it's just a click sound which is automatically invoked at the start (which I don't mind if it's silenced). So I use:
const clickSound = new Audio('click.wav');
clickSound.play().catch(function (error) {
console.log("Chrome cannot play sound without user interaction first")});
to get rid of the error.
I had some issues playing on Android Phone.
After few tries I found out that when Data Saver is on there is no auto play:
There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.
Source
I encountered a similar error with while attempting to play an audio file. At first, it was working, then it stopped working when I started using ChangeDetector's markForCheck method in the same function to trigger a re-render when a promise resolves (I had an issue with view rendering).
When I changed the markForCheck to detectChanges it started working again. I really can't explain what happened, I just thought of dropping this here, perhaps it would help someone.
You should have added muted attribute inside your videoElement for your code work as expected. Look bellow ..
<video id="IPcamerastream" muted="muted" autoplay src="videoplayback%20(1).mp4" width="960" height="540"></video>
Don' t forget to add a valid video link as source
Open chrome://settings/content/sound
Setting No user gesture is required
Relaunch Chrome
Audio Autoplay property does not work in MS Edge
Type Chrome://flags in the address-bar
Search: Autoplay
Autoplay Policy
Policy used when deciding if audio or video is allowed
to autoplay.
– Mac, Windows, Linux, Chrome OS, Android
Set this to "No user gesture is required"
Relaunch Chrome and you don't have to change any code

Change firefox playback bar into a onclick button for audio

SAME ISSUE! As we all know firefox and audio is a problem because of patents and such. I found this little code on the internet to play my sounfile.
I would like to play multiple files instead of just one while having the display bar not show up in the browser
you can change the player width to 0 but than the user can not click the play button :P
Is there a way of possibly having the sound play on click of a link or button.
Please note. Do not give me codes that have no compatibility outside chrome and ie.
HTML
<audio id="audioplayer" preload controls loop style="width:400px;">
<source src="sounds/sound1.mp3">
<source src="sounds/sound1.caf">
</audio>
Javascript
<script type="text/javascript">
var audioTag = document.createElement('audio');
if (!(!!(audioTag.canPlayType) && ("no" != audioTag.canPlayType("audio/mpeg")) && ("" != audioTag.canPlayType("audio/mpeg")))) {
AudioPlayer.embed("audioplayer", {soundFile: "sounds/sound1.mp3"});
}
</script>
RECAP:
Have the sound play on a button or link click.
Have multiple sounds available to play (not just one)
Compatibility with firefox
non visible soundbar.
Still learning myself. But this is a button, with a script to play an audio file. (part of my own solution) Plays only 1 sound at a time, but doesn't show anything about it.
You could also make a funtion like this, without setting the src, using the pause() command.
currenttime is used to change the part where the audio file was.
Sound play button<br>
<script>
sound = new Audio();
function playSnd(soundSrc) {
sound.src = soundSrc;
sound.play();
}
</script>

Categories