How to make audio play on body onload? - javascript

Yesterday I downloaded a responsive navbar tutorial and saw that the author had used button click sound using JavaScript.
So I try the code (copying it) and was able to make it too. When the button is clicked the background music plays well. But when I try adding the same code to body onload function the music din't play.
So, I thought the code has some error but suddenly I opened the HTML file from Opera Mini for Android and the background music appeared. The code which isn't working in advanced browsers like Chrome is working in Opera Mini. Why is this happening?
<!DOCTYPE html>
<head>
<title>Untitled</title>
<meta charset="UTF-8"/>
<link rel="stylesheet" href="" type="text/css"/>
<script>
function stir0(){
var bbs = new Audio('media/background.ogg');
bbs.play();
alert('bb');
}
function pl(){
var Loops = new Audio('media/button_click.ogg');
Loops.play();
}
</script>
</head>
<body onload="stir0()">
<button id="clk" onClick="pl()">Here</button>
</body>
</html>

As of April 2018, Google had changed their Autoplay Policy. It was implemented in Chrome v.66.
Relevant snippet from the Policy:
Chrome's autoplay policies are simple:
Muted autoplay is always allowed.
Autoplay with sound is allowed if:
User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
On mobile, the user has added the site to their home screen.
Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
The way I understand it, and it seems to be reflected in your experience: Chrome browser mutes any autoplayed audio if no action of the user had been made with the domain that specificly requests the audio to be played. Once a user has made a positive interaction, the rules soften and the media may be played without consent renewal.

You can do the first one (the background music) with pure HTML:
<audio autoplay>
<source src="media/background.ogg" type="audio/ogg">
</audio>
The second one (the button click) you do like this:
//JS
var Loops = new Audio("media/button_click.ogg");
//Make sure this is a GLOBAL variable.
And in HTML:
<!--HTML-->
<button id="clk" onClick="Loops.play()">Here</button>

Related

How do I force audio to autoplay on chrome and firefox?

I'm trying to add autoplaying music to a tumblr theme, but Chrome and Firefox both prevent autoplaying audio by default. How do I circumvent this?
Currently, to hear the autoplaying music, a user would have to change their personal browser settings to allow autoplay. Is there a workaround I can use to make the page play audio even if they have sound set to automatic (in Chrome) or autoplay blocked (in Firefox)?
Tumblr themes allow HTML, CSS, and Javascript, so I'd be happy for a solution using any of those. Ideally I would like my autoplay solution to allow multiple songs in a playlist, if possible.
I tried adding an invisible iframe, but that didn't work; I'm not sure whether it was the third-party audio player I'm using, or just that the iframe technique doesn't work at all anymore.
You can't circumvent auto-play from being blocked. There has to be some user interaction before the audio can play. This is the same for both HTML <audio> element as well as the web-audio API's audioContext
There's some reading about this on MDN Autoplay guide for media and Web Audio's API
You can try to play the audio on javascript onload.
Example:
HTML:
<audio controls id="horseAudio">
<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>
JavaScript:
window.onload = function (){
document.getElementById("horseAudio").play();
}
I do not think there is a way around autoplay being deactivated until there is user interaction. I was working on a project with similar problem and I decided to put a "begin" button on it to direct the user to click it. By clicking it (click event listener), they would have satisfied an interaction and it would then play my animations and audio.

Disable fullscreen on double-click?

I have an app which loads a webpage in a webview2 control (Edge Chromium), the page it's loading simply contains a html5 video tag with source and a bit of css for styling.
The css I'm using makes the video take up the full area of the browser page which is working fine, but I want to disable the ability to enter fullscreen (as in, taking up full area of desktop).
I can hide the fullscreen button in css by doing:
::-webkit-media-controls-fullscreen-button {
display: none !important;
}
But the video can still enter fullscreen when double-clicked.
I've tried moving the video to a secondary page sourced in an iframe with donotallowfullscreen but this still doesn't work, double-clicking still results in fullscreen.
<iframe src="Player.html" allow="autoplay; encrypted-media" donotallowfullscreen></iframe>
What else can I try to prevent the video from entering fullscreen? I've tried searching around on Google but all of the results are in reference to Youtube's video embedding.
Not sure why necessary, but here's full reproducible code....
Index.html
<html>
<body>
<iframe donotallowfullscreen src="Iframe.html"></iframe>
</body>
</html>
Iframe.html
<html>
<body>
<video controls src="video.mkv"></video>
</body>
</html>
There is the controlsList attribute which is in the process of being defined, but there are still some issues to sort out before it's official, and currently it seems to be implemented only in Blink browsers.
video{ max-height: 100vh; }
<video controls
src="https://upload.wikimedia.org/wikipedia/commons/a/a4/BBH_gravitational_lensing_of_gw150914.webm"></video>
I didn't checked for IE, but for Safari, they don't even respect the allow of an <iframe> when the fullscreen request has been made by the <video>'s controls, because this fullscreen mode is not the one defined by the Web-API, but rather a native mode. This is also why in this browser we can't even call document.[vendor]ExitFullscreen() (in Firefox this would work because their current UI is using the Web-API).
So the only way to make this work in all browsers would be to make your own controls entirely, and to block the clicks on your <video> element (pointer-events: none).
Just I added controlsList="nofullscreen" attribute. But playing the video on click on the center of won't work. So I added onclick="vd.play()" attribute. <video id="vd" src="video.mp4" onclick="vd.play()" disablePictureInPicture controls controlsList="nofullscreen"></video>

Unsuccessful attempt in adapting audio-visualizer into codepen...need advise

I tried to adopt this audio visualizer from https://github.com/wayou/audio-visualizer-with-controls onto codepen.io. These are the problems I encountered.
1- The visualizer (bar graph type display) is not working on the canvas field.
2 -There is no sound even though the audio player is playing.
Here is the link to my file in codepen http://codepen.io/cgyc8866/pen/wGRqLw
Here is the HTML file. The CSS and JS file can be viewed in codepen at the above link.
<html>
<head>
<title>audio visualizer with audio element</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h3>audio visualizer with controls</h3>
<p>star me on github </p>
<canvas id='canvas' width="800" height="350"></canvas>
<br>
<br>
<audio src="http://wayou.github.io/audio-visualizer-with-controls/assets/sample.mp3" id="audio" controls>audio element not supported</audio>
<script src="main.js"></script>
</body>
I hope someone can take a look. I like to get this program working in codepen or at least to know why it is not working. Thank you in advance.
For audio visualization Web Audio API is required and that will require in turn the audio source to comply with cross-origin usage requirements.
This means you need to either upload the audio to the same server and location (origin) as the page using it, or use an external service such as a CDN that allow cross-origin usage.
A tip: since the audio is located on GitHub you can do the following:
Use for example rawgit.com to create a CDN link for it (I am not affiliated with them)
rawgit.com allows cross-origin usage, but to request this you need to add a crossOrigin attribute to the audio tag.
So, in sum:
Modifed pen here
<audio crossOrigin="anonymous"
src="https://cdn.rawgit.com/wayou/audio-visualizer-with-controls/gh-pages/assets/sample.mp3"
id="audio" controls>
audio element not supported
</audio>
(it might take a few second to preload the audio)
The audio can now be used as source for Web Audio API/the visualizer. Note that Web Audio API is not available to IE users.
(Make sure to read the terms of use with the CDN before publishing it.)

Cannot get WebAudio to play through iOS 8

I have been trying to get WebAudio working in Safari on iOS8 (i have succesfully got it working in Windows and on Android devices).
It is my understanding that you cannot automatically play webaudio through Safari on iOS, but instead you must trigger the first WebAudio call through a user action (e.g. a button press). Then once this first user-driven action is done, WebAudio will work.........Apparantly.
So i have a button set up (using JQM) like this:
Enable Audio<hr />
"PlayDing" is a function which looks like this:
function PlayDing(DingType) {
var sound = new Audio('../../UI/Audio/' + DingType + '.mp3').play();
}
The idea is that by clicking the "Enable Audio" button, this triggers a user interaction to play an mp3 file (which is just 1 second of silence) and then subsequent audio events will just work.
Any ideas why this is not working on iOS8 / Safari?
EDIT:
If i change my JQM button to play a proper ding sound, it works fine and my iPad plays the ding.
EDIT 2:
This is nothing to do with playing audio files from my iPad's music library. This is about playing files / resources that are part of the website.
"It is my understanding that you cannot automatically play webaudio through Safari on iOS, but instead you must trigger the first WebAudio call through a user action (e.g. a button press). Then once this first user-driven action is done, WebAudio will work.........Apparantly."
You are completely right about the handling of the playing. To avoid playing unwanted sounds or unwanted download of sounds onto users devices possibly using up monthly data - a soundplay has to be called in the same stack as the user's touch/click.
There are multiple of things you have to deal with to make sure all your users can reliably play the sound. One thing is it has to be downloaded before you play it. To achieve this we use a technique called preloading.
You also have to take into account that not all users support the same audio format.
An example of your HTML and Javascript could be as follows:
Javascript:
function PlayDing(DingType) {
//Get a reference to the audio element
var sound = document.getElementById(DingType);
//Play it
sound.play();
}
HTML:
<body>
<!--Declare the sounds in as many formats as possible and let the user's browser handling what sound to play & caching -->
<audio id="Silent" preload="auto">
<source src="'../../UI/Audio/silent.ogg" type="audio/ogg">
<source src="'../../UI/Audio/silent.wav" type="audio/wav">
<source src="'../../UI/Audio/silent.aac" type="audio/mpeg">
</audio>
Enable Audio
<hr />
</body>

Issue with the flash fallback of VideoJs with Firefox

I have try to add videoJs to my site to play MP4 files, all works perfectly in Chrome but when I go to Firefox (which doesn't support MP4 files) the flash player stay on a black screen and buttons do nothing.
Simple question: why?
I don't understand, websites like vine.co or instagram use videoJs with no issue but for me this is not the case.
So I tried to change the tech order, now Flash always try to read the video but even on chrome nothing append.
This is my test code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script src="http://vjs.zencdn.net/4.0/video.js"></script>
<script>
videojs.options.flash.swf = "video-js.swf"
</script>
</head>
<body>
<video id="video" src="http://domain.com/flash/video.mp4" control></video>
<script type="text/javascript">
jQuery(function() {
var player = videojs('video', {"controls": true, "autoplay": false, "preload": "auto", "techOrder": ["flash", "html5"]});
console.log(player);
});
</script>
</body>
</html>
All the files (the swf player, the MP4 video, and the html file) are in the same folder named 'flash'.
Can you help me?
A few things to try here:
Make sure you're loading the video-js css file.
Add the "video-js" and skin classes to your video object as described here (also, it is "controls", not "control"): https://github.com/videojs/video.js/blob/0020ba15b9ae2b60e51d4d8d2751ffa31d18694d/docs/guides/setup.md
If you're loading video js from the CDN, you don't need to set the flash.swf option. That may be causing an issue as well.
You shouldn't need to set the techOrder to get Firefox to behave, and you definitely don't need a corresponding video file for each type of "Tech". Flash will play the fallback in mp4 as long as it's above version 9 or so.
I did run into an issue on Firefox where the Flash fallback would play the video but the video would be blank (audio would play) when I included a "ready" event. I was able to get around this by firing a blur event on the $(this) object. That may be helpful to you if you need to use ready.
You need a flv Version of your Video when you want to deliver it through flash.
It could be usefull to offer another webm Version of your Video. This should bei played in Firefox and Chrome.
For every Tech you need the correspondenting videofile.

Categories