Fallback solution for HTML <audio> and legacy browsers - html

I am working on creating a sound board with various audio clips.
Rather than using the standard HTML5 audio controls, I want to style each button with some title text, so that when a user presses a button, the associated clip plays.
Everything is working fine in HTML 5 browsers (Chrome, Firefox, Safari, and IE9+), using the following code:
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
that.play();
}));
});
});
</script>
<!-- Sample Audio Clip -->
<audio controls preload="auto" autobuffer title="Sounds of Laughter">
<source src="assets/clips/1.mp3" />
<source src="assets/clips/1.ogg" />
</audio>
However, this solution is not supported on non-HTML 5 compliant browsers like Internet Explorer 8.
I am looking for some sort of workaround solution that will allow me to either (a) detect if a browser doesn't support the HTML 5 tag and redirect to an alternate version of the sound board or (b) use a fallback (flash, etc.) with custom styling on the button if support is not present.

You should use both Modernizr as Garret said and jPlayer
Check Garrett's answer on how to check for compatibility. Though I don't see why it would be useful if your only goal is to seamlessly play HTML5 or Flash based on compatibility. jPlayer does it automatically.
You just have to instantiate it:
$("#music").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", {
mp3:"music.mp3",
oga:"music.ogg"
});
},
swfPath: "js",
supplied: "mp3, oga"
});
The following depends on the interface you want to use. jPlayer has some skins, but you can modify them to your will or just create a whole interface from scratch like I do and use jPlayer methids

You should take a look at the Modernizr script library. This will allow you to perform conditional logic based on what HTML5 features are supported by the browser. For example, you could do something like this:
var audio = new Audio();
audio.src = Modernizr.audio.ogg ? 'background.ogg' :
Modernizr.audio.mp3 ? 'background.mp3' :
'background.m4a';
audio.play();
Documentation can be found here: http://modernizr.com/docs/#features-html5.

I found another example which I have slightly modified for MP3 to OGG fallback. It uses the canPlayType method:
var audiofile = 'example.mp3';
var audioTag = document.createElement('audio');
if (!(!!(audioTag.canPlayType) && ("no" != audioTag.canPlayType("audio/mpeg"))
&& ("" != audioTag.canPlayType("audio/mpeg")))) {
audiofile = audiofile.replace('.mp3','.ogg');
}

Related

How to play .mov files in video tag

I am trying to play .mov videos in HTML5 browser. I have tried everything available over the internet e.g.
attribute "controls"
using <source> tag
using src attribute with even changing MIME type to mp4.
But Nothing worked for me. Can anyone suggest solution for this?
The Video tag only supports certain filetypes. The .MOV container uses the Quicktime codec which is proprietary Apple software and is not on the list of Media formats supported by the HTML audio and video elements. I'd suggest transcoding the footage to .MP4 and using that instead.
My suggestion is converting the file to .mp4. There are several softwares you can use to do so. I suggest Handbrake.
https://handbrake.fr/
For jQuery, try this code. What it does it get the data from the input tag and instantiates a FileReader instance. We add an event listener to this instance and we append a <source> tag as child to the <video> tag. We are able to get the duration once the data has been loaded. Adding a type="video/mp4" attribute to the source tag is a small enhancement that would work on most .mov files, but not all (untested). This is an enhancement to another SO answer located here.
$(document).ready(function() {
var data = $('#file-input')[0]; // File from <input type="file"> tag
var reader = new FileReader();
reader.addEventListener('load', function() {
var video = $('<video class="uploaded_video_src" controls></video>');
if (reader.result) {
$('.uploaded_video_src').append(`<source src="${reader.result}" type="video/mp4">`); // Add type attr for support for some .mov files
video.on('loadedmetadata', function() {
console.log('duration:', $(this)[0].duration);
});
}
});
});

How to make HTML5 audio play exactly once on clicking?

I'm putting together an online evaluation survey of synthesized speech. Part of the test requires that listeners are only allowed to hear a given WAV file play once (as an experimental control).
I've already figured out how to simply embed an audio clip with controls, so that it can be played several times:
<audio controls>
<source src="http://mypage.com/my_sound.wav" type="audio/wav">
Your browser does not support the audio element
</audio>
Furthermore, I've seen that some HTML questions have attempted to resolve the error of HTML audio playing back only once:
Audio played once only in Google Chrome in html
JavaScript + HTML5: Audio will only play once under certain circumstances
However, my question is how to code this (play HTML audio just once on-click) intentionally? Everything I've seen treats it as a bug to be fixed, rather than an intentional goal.
Cheers!
I've been looking for this one too.
You have a few options.
The key to this stop is the onended event, which as you might expect, triggers when the fat lady stops singing.
<audio id="gilda">
<source url="epic-aria.mp3">
</audio>
var fatLady = document.getElementById('gilda');
fatLady.onended = function() {
fatLady.pause();
fatLady.currentTime = 0; // << only needed if you're cutting off the sound misstep (before the end) and need to return to the beginning - but you might need it. Since you are doing some gaming, I figured that might come up...
};
There is also a jQuery way, which I am currently using. jQuery doesn't use onended, however - it uses ended instead...
var fatLady = $('#gilda');
fatLady.bind('ended', function(event) {
fatLady
.pause()
.currentTime = 0; // << haven't field-tested this yet, but jquery didn't yell at me about it.
});
Let me know if you run into any hiccups.

How can i embed youtube video into html5 <video> tag [duplicate]

I'm trying to put a YouTube video source into the HTML5 <video> tag, but it doesn't seem to work. After some Googling, I found out that HTML5 doesn't support YouTube video URLs as a source.
Can you use HTML5 to embed YouTube videos? If not, is there any workaround?
This answer does not work anymore, but I'm looking for a solution.
As of . 2015 / 02 / 24 . there is a website (youtubeinmp4) that allows you to download youtube videos in .mp4 format, you can exploit this (with some JavaScript) to get away with embedding youtube videos in <video> tags. Here is a demo of this in action.
##Pros
Fairly easy to implement.
Quite fast server response actually (it doesn't take that much to retrieve the videos).
Abstraction (the accepted solution, even if it worked properly, would only be applicable if you knew beforehand which videos you were going to play, this works for any user inputted url).
##Cons
It obviously depends on the youtubeinmp4.com servers and their way of providing a downloading link (which can be passed as a <video> source), so this answer may not be valid in the future.
You can't choose the video quality.
###JavaScript (after load)
videos = document.querySelectorAll("video");
for (var i = 0, l = videos.length; i < l; i++) {
var video = videos[i];
var src = video.src || (function () {
var sources = video.querySelectorAll("source");
for (var j = 0, sl = sources.length; j < sl; j++) {
var source = sources[j];
var type = source.type;
var isMp4 = type.indexOf("mp4") != -1;
if (isMp4) return source.src;
}
return null;
})();
if (src) {
var isYoutube = src && src.match(/(?:youtu|youtube)(?:\.com|\.be)\/([\w\W]+)/i);
if (isYoutube) {
var id = isYoutube[1].match(/watch\?v=|[\w\W]+/gi);
id = (id.length > 1) ? id.splice(1) : id;
id = id.toString();
var mp4url = "http://www.youtubeinmp4.com/redirect.php?video=";
video.src = mp4url + id;
}
}
}
###Usage (Full)
<video controls="true">
<source src="www.youtube.com/watch?v=3bGNuRtlqAQ" type="video/mp4" />
</video>
Standard video format.
###Usage (Mini)
<video src="youtu.be/MLeIBFYY6UY" controls="true"></video>
A little less common but quite smaller, using the shortened url youtu.be as the src attribute directly in the <video> tag.
I have created a realtively small (4.89 KB) javascript library for this exact functionality.
Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/
It's as simple as:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader#2.0.0/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/
What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.
UPDATE June 2021
YouTube have recently updated their API which has broken previous versions of this package. Please now use versions 4.0.1 and up! Updated example:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader#4.0.1/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
https://jsfiddle.net/thelevicole/5g6dbpx3/2/
The <video> tag is meant to load in a video of a supported format (which may differ by browser).
YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.
YouTube does offer a developer API to embed a youtube video into your page.
I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/
And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started
The Code can also be found below
In your HTML:
<div id="player"></div>
In your Javascript:
var onPlayerReady = function(event) {
event.target.playVideo();
};
// The first argument of YT.Player is an HTML element ID.
// YouTube API will replace my <div id="player"> tag
// with an iframe containing the youtube video.
var player = new YT.Player('player', {
height: 320,
width: 400,
videoId : '6Dc1C77nra4',
events : {
'onReady' : onPlayerReady
}
});
Step 1: add &html5=True to your favorite youtube url
Step 2: Find <video/> tag in source
Step 3: Add controls="controls" to video tag: <video controls="controls"..../>
Example:
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&itag=43&ipbits=0&signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&sver=3&ratebypass=yes&expire=1300417200&key=yt1&ip=0.0.0.0&id=37da319914f6616c"></video>
Note there seems to some expire stuff. I don't know how long the src string will work.
Still testing myself.
Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.
how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...
<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>
the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo
youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...
the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...
In case anyone stumbles upon this question, a neat way to embed YouTube video is to use embed tag, like so:
<embed src="https://www.youtube-nocookie.com/embed/DelkRGZCtTs" width="100%" height="333">
The easiest answer is given by W3schools.
https://www.w3schools.com/html/html_youtube.asp
Upload your video to Youtube
Note the Video ID
Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.
The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:
<iframe type="text/html"
width="640"
height="385"
src="http://www.youtube.com/embed/VIDEO_ID"
frameborder="0">
</iframe>

Create a html5 audio and play it doesn't work

I want create a html5 audio in dynamic and play it,here is the code:
function playAnotherMusic(playUrl){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', playUrl);
audioElement.setAttribute('controls', true);
audioElement.setAttribute('preload', true);
audioElement.setAttribute('type', 'audio/mpeg');
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);
console.log(playUrl);
audioElement.load();
}
However it doesn't work,the firebug assigin me "HTTP "Content-Type" of "audio/mpeg" is not supported."
how can I solve this problem?
You can't play mp3 files in firefox, it does not support them, you need an ogg version for firefox. Unless that changes, good to keep in mind.
Why doesn't Firefox support the MP3 file format in <audio>
You need to append the audio element to the an existing element.
This would be something like
document.getElementById("my_audio_div").appendChild(audioElement);
Idealy, this should be done before you add the event listener, but after setting all the attributes
Also try audio/mp3 instead:
audioElement.setAttribute('type', 'audio/mp3');

Show Youtube video source into HTML5 video tag?

I'm trying to put a YouTube video source into the HTML5 <video> tag, but it doesn't seem to work. After some Googling, I found out that HTML5 doesn't support YouTube video URLs as a source.
Can you use HTML5 to embed YouTube videos? If not, is there any workaround?
This answer does not work anymore, but I'm looking for a solution.
As of . 2015 / 02 / 24 . there is a website (youtubeinmp4) that allows you to download youtube videos in .mp4 format, you can exploit this (with some JavaScript) to get away with embedding youtube videos in <video> tags. Here is a demo of this in action.
##Pros
Fairly easy to implement.
Quite fast server response actually (it doesn't take that much to retrieve the videos).
Abstraction (the accepted solution, even if it worked properly, would only be applicable if you knew beforehand which videos you were going to play, this works for any user inputted url).
##Cons
It obviously depends on the youtubeinmp4.com servers and their way of providing a downloading link (which can be passed as a <video> source), so this answer may not be valid in the future.
You can't choose the video quality.
###JavaScript (after load)
videos = document.querySelectorAll("video");
for (var i = 0, l = videos.length; i < l; i++) {
var video = videos[i];
var src = video.src || (function () {
var sources = video.querySelectorAll("source");
for (var j = 0, sl = sources.length; j < sl; j++) {
var source = sources[j];
var type = source.type;
var isMp4 = type.indexOf("mp4") != -1;
if (isMp4) return source.src;
}
return null;
})();
if (src) {
var isYoutube = src && src.match(/(?:youtu|youtube)(?:\.com|\.be)\/([\w\W]+)/i);
if (isYoutube) {
var id = isYoutube[1].match(/watch\?v=|[\w\W]+/gi);
id = (id.length > 1) ? id.splice(1) : id;
id = id.toString();
var mp4url = "http://www.youtubeinmp4.com/redirect.php?video=";
video.src = mp4url + id;
}
}
}
###Usage (Full)
<video controls="true">
<source src="www.youtube.com/watch?v=3bGNuRtlqAQ" type="video/mp4" />
</video>
Standard video format.
###Usage (Mini)
<video src="youtu.be/MLeIBFYY6UY" controls="true"></video>
A little less common but quite smaller, using the shortened url youtu.be as the src attribute directly in the <video> tag.
I have created a realtively small (4.89 KB) javascript library for this exact functionality.
Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/
It's as simple as:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader#2.0.0/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/
What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.
UPDATE June 2021
YouTube have recently updated their API which has broken previous versions of this package. Please now use versions 4.0.1 and up! Updated example:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader#4.0.1/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
https://jsfiddle.net/thelevicole/5g6dbpx3/2/
The <video> tag is meant to load in a video of a supported format (which may differ by browser).
YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.
YouTube does offer a developer API to embed a youtube video into your page.
I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/
And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started
The Code can also be found below
In your HTML:
<div id="player"></div>
In your Javascript:
var onPlayerReady = function(event) {
event.target.playVideo();
};
// The first argument of YT.Player is an HTML element ID.
// YouTube API will replace my <div id="player"> tag
// with an iframe containing the youtube video.
var player = new YT.Player('player', {
height: 320,
width: 400,
videoId : '6Dc1C77nra4',
events : {
'onReady' : onPlayerReady
}
});
Step 1: add &html5=True to your favorite youtube url
Step 2: Find <video/> tag in source
Step 3: Add controls="controls" to video tag: <video controls="controls"..../>
Example:
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&itag=43&ipbits=0&signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&sver=3&ratebypass=yes&expire=1300417200&key=yt1&ip=0.0.0.0&id=37da319914f6616c"></video>
Note there seems to some expire stuff. I don't know how long the src string will work.
Still testing myself.
Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.
how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...
<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>
the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo
youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...
the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...
In case anyone stumbles upon this question, a neat way to embed YouTube video is to use embed tag, like so:
<embed src="https://www.youtube-nocookie.com/embed/DelkRGZCtTs" width="100%" height="333">
The easiest answer is given by W3schools.
https://www.w3schools.com/html/html_youtube.asp
Upload your video to Youtube
Note the Video ID
Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.
The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:
<iframe type="text/html"
width="640"
height="385"
src="http://www.youtube.com/embed/VIDEO_ID"
frameborder="0">
</iframe>