<Audio> fallback through Javascript - javascript

I want to understand how to implement HTML5 <audio> fallback using Javascript...
i.e. I have a div on my page, to which , I dynamically append <embed> tag when "Play audio" link is clicked currently..
i.e. I currently use
function playSound(audioUrl)
{
var x = document.getElementById("playAudio");
x.innerHTML = '<EMBED src="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>';
}
I want to have the same thing implemented using the HTML5 <audio> tag, But want to fallback to embed when HTML5 audio tag is not supported. How can I implement the same using JS given that the Audio URL is kind of dynamic ?
My intention is it should work on older as well as newer browsers..like IE6,7,8; FF 3,4; Chrome; Safari 4,5 on MAC, Safari on iPad..

You could use Modernizr to detect audio support.
If you don't want to include that library for a simple thing, this should do it...
var audioSupport = document.createElement('audio').hasOwnProperty('src');
jsFiddle.
So that would be...
function playSound(audioUrl) {
var audioSupport = document.createElement('audio').hasOwnProperty('src'),
x = document.getElementById("playAudio");
if (audioSupport) {
var audio = document.createElement('audio');
audio.src = audioUrl;
x.appendChild(audio);
audio.play();
} else {
// Or you could use proper DOM methods...
x.innerHTML = '<EMBED src="' + audioUrl + '" autostart=true loop=false volume=100 hidden=true>';
}
}
jsFiddle.

Related

Load different video in HTML5 video player

I have an HTML5 video tag that I dynamically load. Here's my HTML:
<video id="video" width="640" height="480" controls autoplay>
<source id="source" src="" type="video/mp4">
</video>
Here is my JavaScript for loading the video:
function RunVideo(index) {
var grid = document.getElementById("ctl00_ContentPlaceHolder1_gvPresentations");
var cell = grid.rows[(+index) + 1].cells[2].innerHTML;
var player = document.getElementById('video');
var mp4Vid = document.getElementById('source');
var movie = cell;
player.pause();
mp4Vid.setAttribute('src', movie);
player.load();
player.play();
}
The first time I load a video (from a grid view) it works fine. But any subsequent ones I try to load I get the following message in the video player:
Error: Unsupported video type or invalid file path.
How can I correctly unload the current video in order to reload a new one?
Edit
It seems to be an IE only bug. It does work in other browsers like a charm.
It is able to play each video individually on load (i.e if no other src have been set before).
The links and code are ok then.
It throws a MEDIA12899: AUDIO/VIDEO: Unknown MIME type. error.
Edit:
After I tested with this fiddle, the bug doesn't raise, so my assumptions were incorrect.
Which leaves you with the only choice of trying to re-encode your videos.
Original answer:
It seems you are facing an IE bug, when setting the source element with different codecs(not type).
I think that the browser automatically assigns for himself the codec parameter, in the type attribute and doesn't update it when the new src is set.
Even if all your videos are encapsulated in .mp4, the codecs may vary.
You can find a list of codecs that IE does support here. Basically, .webm, '
H.264 high profile' and H.264 baseline profile.
One possible workaround you may try, if my assumptions are correct, is to create a new sourceelement each time you call your RunVideo function.
function RunVideo(index) {
var grid = document.getElementById("ctl00_ContentPlaceHolder1_gvPresentations");
var cell = grid.rows[(+index) + 1].cells[2].innerHTML;
var player = document.getElementById('video');
var oldMp4Vid = document.getElementById('source');
var movie = cell;
var newmp4Vid = document.createElement('source')
newMp4Vid.src = cell;
player.removeChild(oldMp4Vid);
player.appendChild(newMp4Vid);
player.load();
}
I'm not sure it will do the trick and I'm not sure what the specs tells about setting <source> new src on the flow like that, but if this problem is only present in IE, it's probably a bug from them, maybe you could fill a bug report.
Alternatively, you could re-encode your videos with the exact same codec.

safari browser doesn’t support HTML5 audio tag in ipad/iphone,Android

I am working on a project based on jquery animation its animation works fine on desktop (Firefox,chrome,opera,IE) also support HTML 5 audio tag but in Ipad/iphone/ Android safari audio tag doesn’t support.Its works fine on Ipad/iphone/ Android firefox.i have searched it in many forum don’t get desire Result. I have used this function :
function playmusic(file1,file2)
{
document.getElementById('music11').innerHTML='<audio id="music1"><source src="'+file1+'" type="audio/ogg"><source src="'+file2+'" type="audio/mpeg"></audio>';
$("#music1").get(0).play();
}
I have called function like : playmusic(2.ogg','2.mp3');
If I give autoplay in audio tag it works but play method not working and I have to use play method as in my application needs sound in particular event see the link
http://solutions.hariomtech.com/jarmies/
I have also changed my function and give direct audio tag in div and call function the same problem I face as I mentioned above. I need sound play in background without any click.if I use auto play method so it play sound only one time but I need sound multiple time on event.
Try to add an autoplay attribute on the audio tag:
function playmusic(file1, file2) {
document.getElementById('music11').innerHTML='<audio autoplay id="music1"><source src="'+file1+'" type="audio/ogg"><source src="'+file2+'" type="audio/mpeg"></audio>';
}
I would however recommend building a proper element and insert that into the DOM - something like this:
function playmusic(file1, file2) {
var audio = document.createElement('audio');
audio.preload = 'auto';
audio.autoplay = true;
if (audio.canPlayType('audio/ogg')) {
audio.src = file1;
}
else if (audio.canPlayType('audio/mpg')) {
audio.src = file2;
}
document.getElementById('music11').appendChild(audio);
}

Pausing video doesn't stop audio in html5 video tag

I'm pausing a video using its pause() method.. the problem is that the audio continues playing... I also tried pausing it from the Javascript Console in Firefox... nothing happens. The video is in .ogg format and is not even playing in Chrome (because I think it's not supported).
I hosted the video on Amazon S3 and it is streaming perfectly. I'm creating the element dynamically, loading its info from a JSON request.
Here is some code:
function showVideo() {
var video = videodata;
var videobox = $('#videobox').first();
var videoplayer = document.getElementById('videoplayer');
if (video.Enabled) {
if ((videoplayer != null && videoplayer.currentSrc != video.Location) || videoplayer == null) {
console.log('Creating video elem');
videobox.empty();
videobox.append('<video id="videoplayer" preload="auto" src="' +
video.Location + '" width="100%" height="100%" autoplay="autoplay" loop="loop" />');
videobox.show();
}
} else {
if (videoplayer != null) {
videoplayer.pause();
console.log('Pausing video...');
}
console.log('Deleting video elem');
videobox.hide();
videobox.empty();
}
}
I already posted a similar question before... but now I'm using other browsers, so I thought I have to create a new question.
Here is the working code (thanks to the user heff!)
function showVideo() {
var video = videodata;
var videobox = $('#videobox').first();
var videoplayer = document.getElementById('videoplayer');
if (video.Enabled) {
if ((videoplayer.src != video.Location) || videoplayer.src == '') {
console.log('Playing video: ' + video.Location);
videoplayer.src = video.Location;
videoplayer.load();
videoplayer.play();
videobox.show();
}
} else {
if (videoplayer.src != '') {
console.log('Pausing video...');
videoplayer.pause();
videoplayer.src = '';
videobox.hide();
}
}
}
I had a similar issue which was resolved with really wonderful coders. Check out this post. It might be of great use. HTML5 Video Controls do not work
If you are using html attribute:
<video id="yourvideoID" poster="Pic.jpg" loop autoplay controls width="100%">
<source src="//example.website/InnovoThermometer.mp4" type="video/mp4">
</video>
Remove autoplay.
Then use jquery to use autoplay instead:
$(document).ready(function() { $("#bigvid3").get(0).play(); });
As for the source there are multiple locations:
html5 video playing twice (audio doubled) with JQuery .append()
and
Auto-play an HTML5 video on Dom Load using jQuery
My guess would be that showVideo is being called twice some how and creating two copies, one of which keeps playing even after you call pause on the other.
In your code, the videoplayer var won't refer to the video tag you create later with append, it will point to whatever had that id before, which I'm assuming gets removed when you empty the box, but might stick around in memory (and continue to play sound).
Just my best guess, but either way it'd be better to use the video element's API to set the source and other parameters rather than emptying the box and rebuilding the tag.
videoplayer.src = video.Location;
videoplayer.autoplay = true;
// etc.
Also, 100% isn't a valid value for the width/height attributes. You'll need to use CSS to make the video stretch to fill an area.

How to play a mp3 using Javascript? [duplicate]

This question already has answers here:
Play mp3 file using javascript
(3 answers)
Closed 10 years ago.
I have a directory on my website with several mp3's.
I dynamically create a list of them in the website using php.
I also have a drag and drop function associated to them and I can select a list of those mp3 to play.
Now, giving that list, how can I click on a button (Play) and make the website play the first mp3 of the list? (I also know where the music is on the website)
new Audio('<url>').play()
If you want a version that works for old browsers, I have made this library:
// source: https://stackoverflow.com/a/11331200/4298200
function Sound(source, volume, loop)
{
this.source = source;
this.volume = volume;
this.loop = loop;
var son;
this.son = son;
this.finish = false;
this.stop = function()
{
document.body.removeChild(this.son);
}
this.start = function()
{
if (this.finish) return false;
this.son = document.createElement("embed");
this.son.setAttribute("src", this.source);
this.son.setAttribute("hidden", "true");
this.son.setAttribute("volume", this.volume);
this.son.setAttribute("autostart", "true");
this.son.setAttribute("loop", this.loop);
document.body.appendChild(this.son);
}
this.remove = function()
{
document.body.removeChild(this.son);
this.finish = true;
}
this.init = function(volume, loop)
{
this.finish = false;
this.volume = volume;
this.loop = loop;
}
}
Documentation:
Sound takes three arguments. The source url of the sound, the volume (from 0 to 100), and the loop (true to loop, false not to loop).
stop allow to start after (contrary to remove).
init re-set the argument volume and loop.
Example:
var foo = new Sound("url", 100, true);
foo.start();
foo.stop();
foo.start();
foo.init(100, false);
foo.remove();
//Here you you cannot start foo any more
You will probably want to use the new HTML5 audio element to create an Audio object, load the mp3, and play it.
Due to browser inconsistencies, this sample code is a bit lengthly, but it should suit your needs with a bit of tweaking.
//Create the audio tag
var soundFile = document.createElement("audio");
soundFile.preload = "auto";
//Load the sound file (using a source element for expandability)
var src = document.createElement("source");
src.src = fileName + ".mp3";
soundFile.appendChild(src);
//Load the audio tag
//It auto plays as a fallback
soundFile.load();
soundFile.volume = 0.000000;
soundFile.play();
//Plays the sound
function play() {
//Set the current time for the audio file to the beginning
soundFile.currentTime = 0.01;
soundFile.volume = volume;
//Due to a bug in Firefox, the audio needs to be played after a delay
setTimeout(function(){soundFile.play();},1);
}
Edit:
To add Flash support, you would append an object element inside the audio tag.
You can use <audio> HTML5 tag to play audio using JavaScript.
But this is not cross-browser solution. It supported only in modern browsers. For cross-browser compatibility you probably need to use Flash for that (for example jPlayer).
Browsers compatibility table is provided at link I mentioned above.
You could try SoundManager 2: it will transparently handle the <audio> tag wherever it's supported, and use Flash wherever it isn't.
Assuming that the browser supports MP3 playback and is fairly new to support newer JavaScript features, I would suggest taking a look at jPlayer.
You can see a short demo tutorial on how to implement it.
Jquery plugin for audio mp3 player http://www.jplayer.org/0.2.1/demos/
Enjoy it ;)
<html>
<head>
<title>Play my music....</title>
</head>
<body>
<ul>
<li>
<a id="PlayLink" href="http://www.moderntalking.ru/real/music/Modern_Talking-You_Can_Win(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">U Can Win</a>
</li>
<li>
<a id="A1" href="http://www.moderntalking.ru/real/music/Modern_Talking-Brother_Louie(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">Brother Louie</a>
</li>
</ul>
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
</body>
</html>

How to play a notification sound on websites?

When a certain event occurs, I want my website to play a short notification sound to the user.
The sound should not auto-start (instantly) when the website is opened.
Instead, it should be played on demand via JavaScript (when that certain event occurs).
It is important that this also works on older browsers (IE6 and such).
So, basically there are two questions:
What codec should I use?
What's best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)
2021 solution
function playSound(url) {
const audio = new Audio(url);
audio.play();
}
<button onclick="playSound('https://your-file.mp3');">Play</button>
Browser support
Edge 12+, Firefox 20+, Internet Explorer 9+, Opera 15+, Safari 4+, Chrome
Codecs Support
Just use MP3
Old solution
(for legacy browsers)
function playSound(filename){
var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename +'.mp3">';
document.getElementById("sound").innerHTML='<audio autoplay="autoplay">' + mp3Source + oggSource + embedSource + '</audio>';
}
<button onclick="playSound('bing');">Play</button>
<div id="sound"></div>
Browser support
<audio> (Modern browsers)
<embed> (Fallback)
Codes used
MP3 for Chrome, Safari and Internet Explorer.
OGG for Firefox and Opera.
As of 2016, the following will suffice (you don't even need to embed):
let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();
See more here.
One more plugin, to play notification sounds on websites: Ion.Sound
Basic Demo
Advanced Demo
Ion.Sound GitHub Page
Advantages:
JavaScript-plugin for playing sounds based on Web Audio API with fallback to HTML5 Audio.
Plugin is working on most popular desktop and mobile browsers and can be used everywhere, from common web sites to browser games.
Audio-sprites support included.
No dependecies (jQuery not required).
25 free sounds included.
Set up plugin:
// set up config
ion.sound({
sounds: [
{
name: "my_cool_sound"
},
{
name: "notify_sound",
volume: 0.2
},
{
name: "alert_sound",
volume: 0.3,
preload: false
}
],
volume: 0.5,
path: "sounds/",
preload: true
});
// And play sound!
ion.sound.play("my_cool_sound");
How about the yahoo's media player
Just embed yahoo's library
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
And use it like
<a id="beep" href="song.mp3">Play Song</a>
To autostart
$(function() { $("#beep").click(); });
Play cross browser compatible notifications
As adviced by #Tim Tisdall from this post , Check Howler.js Plugin.
Browsers like chrome disables javascript execution when minimized or inactive for performance improvements. But This plays notification sounds even if browser is inactive or minimized by the user.
var sound =new Howl({
src: ['../sounds/rings.mp3','../sounds/rings.wav','../sounds/rings.ogg',
'../sounds/rings.aiff'],
autoplay: true,
loop: true
});
sound.play();
Hope helps someone.
if you want calling event on the code The best way to do that is to create trigger because the browser will not respond if the user is not on the page
<button type="button" style="display:none" id="playSoundBtn" onclick="playSound();"></button>
now you can trigger your button when you want to play sound
$('#playSoundBtn').trigger('click');
if you want to automate the process via JS:
Include somewhere in the html:
<button onclick="playSound();" id="soundBtn">Play</button>
and hide it via js :
<script type="text/javascript">
document.getElementById('soundBtn').style.visibility='hidden';
function performSound(){
var soundButton = document.getElementById("soundBtn");
soundButton.click();
}
function playSound() {
const audio = new Audio("alarm.mp3");
audio.play();
}
</script>
if you want to play the sound just call performSound() somewhere!
Use the audio.js which is a polyfill for the <audio> tag with fallback to flash.
In general, look at https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills for polyfills to the HTML 5 APIs.. (it includes more <audio> polyfills)
var audio = new Audio('audio_file.mp3');
function post()
{
var tval=document.getElementById("mess").value;
var inhtml=document.getElementById("chat_div");
inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
audio.play();
}
this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php
I wrote a clean functional method of playing sounds:
sounds = {
test : new Audio('/assets/sounds/test.mp3')
};
sound_volume = 0.1;
function playSound(sound) {
sounds[sound].volume = sound_volume;
sounds[sound].play();
}
function stopSound(sound) {
sounds[sound].pause();
}
function setVolume(sound, volume) {
sounds[sound].volume = volume;
sound_volume = volume;
}
We can just use Audio and an object together like:
var audio = {};
audio['ubuntu'] = new Audio();
audio['ubuntu'].src="start.ogg";
audio['ubuntu'].play();
and even adding addEventListener for play and ended

Categories