Detect embedded Youtube player captions - javascript

Is it possible to detect whether youtube captions are on or off in an embedded player?
There is currently no way to suppress the captions if users choses to display them. I would like to show a customized message if the captions are on.
In the documentation there is no mention of this as far as I can say.

I have not found this anywhere in their api docs, but with your youtube player object you should be able to do:
player.getOptions("captions") || player.getOptions("cc") //detects if captions were ever loaded at one point.
You can also turn it on via js by:
player.loadModule("captions"); //Works for html5 ignored by AS3
player.loadModule("cc"); //Works for AS3 ignored by html5
to turn it off:
player.unloadModule("captions"); //Works for html5 ignored by AS3
player.unloadModule("cc"); //Works for AS3 ignored by html5
to change which language if the module is loaded:
player.setOption("captions", "track", {"languageCode": "es"}); //Works for html5 ignored by AS3
player.setOption("cc", "track", {"languageCode": "es"}); //Works for AS3 ignored by html5

Easy as pie, you can ;)
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<div id="ytapiplayer">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/v/QRS8MkLhQmM?enablejsapi=1&playerapiid=ytplayer&version=3",
"ytapiplayer", "640", "480", "8", null, null, params, atts);
var stateChange = function(a) {
if (ytplayer.getOptions().indexOf("cc") !== -1) {
alert("closed captions are on");
} else {
alert("closed captions are off");
}
}
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById("myytplayer");
ytplayer.addEventListener("onStateChange","stateChange");
}
</script></body>
</html>
BTW: Google rocks ;)
this should do the trick - please don't use it in production mode - it was just a quick sum-up. You need to listen to the state you want, I'm just alerting at any event ;)

Related

Javascript HTML5 video event canplay not firing on Safari

I have a HTML page including Javascript which is intended to allow a video (actually just audio content in this case) to play using HTTP Live Streaming on any browser. In most cases it uses hls.js but, in the case of Apple products, I need to do things differently as Safari has native HLS support.
The full page is reproduced below but the important lines are these:
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = 'music.m3u8';
video.addEventListener('canplay', startPlaying);
//document.addEventListener('DOMContentLoaded', startPlaying);
}
What should happen is that when the canplay event fires the startPlaying() function is called and this makes visible a button that the user can press to begin playing the video. However, on my friend's iPhone 8plus (iOS 11.3.1), this doesn't work: no button is ever visible. If, instead, I comment out the video.addEventListener() line and replace it with the document.addEventListener() line then it all works fine: the button is made visible and he can play the stream.
Can anyone spot what I'm doing wrong? Could be a rookey mistake as I'm not very experienced with this web/script stuff, gives me nose bleeds... I could, of course, leave it with the DOM load approach but it's not right and I'd rather be right.
<!DOCTYPE html PUBLIC "-//Netscape Comm. Corp.//DTD HTML//EN">
<html>
<script src="hls.js/dist/hls.js"></script>
<head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head>
<body>
<video id="video"></video>
<button id="play" hidden>Loading</button>
<script>
'use strict';
var video = document.getElementById('video');
var playButton = document.getElementById('play');
function startPlaying() {
// For mobile browsers the start of playing has to
// be performed by a user action otherwise it will
// be ignored
playButton.addEventListener('click', function() {
video.play();
video.muted = false;
video.volume = 1;
playButton.innerHTML = "Playing";
});
playButton.hidden = false;
playButton.innerHTML = "Ready to play";
}
if (Hls.isSupported()) {
var hls = new Hls();
hls.loadSource('music.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, startPlaying);
}
// hls.js is not supported on platforms that do not have Media Source Extensions (MSE) enabled.
// When the browser has built-in HLS support (check using `canPlayType`), we can provide an HLS manifest (i.e. .m3u8 URL) directly to the video element through the `src` property.
// This is using the built-in support of the plain video element, without using hls.js.
else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = 'music.m3u8';
video.addEventListener('canplay', startPlaying);
//document.addEventListener('DOMContentLoaded', startPlaying);
}
</script>
</body>
</html>
From the investigations in the other question, the workaround is to wait on the event loadedmetadata, so in my case video.addEventListener('loadedmetadata', startPlaying), as this is the last event you're going to get from the HTML5 video element on Safari unless you're in the user-controlled white list. Confirmed that this works on iOS 11.3.1.

YouTube onStateChange event is suddenly not working

I had everything working fine until about two weeks ago. I haven't changed any code.
function loadYtVideo(video, advert, advert_link, splash, splash_link){
var params = { allowScriptAccess: "always", wmode: "transparent" };
var atts = { id: "eda-player", wmode: "transparent" };
var swfobject;
adv.orig = video;
swfobject.embedSWF("https://www.youtube.com/v/"+adv.orig+"?rel=0&enablejsapi=1&playerapiid=ytplayer","ytapiplayer", "719", "404", "8", null, null, params, atts);
}
function onYouTubePlayerReady(playerId) {
//It's fired
edaplayer = document.getElementById('eda-player');
edaplayer.addEventListener("onStateChange", "playerState");
}
function playerState(state) {
//it's not fired
console.log(state);
}
<div class="adv-video">
<div id="ytapiplayer">
<script>
$(document).ready(function(){
loadYtVideo($.getUrlVar('ytVideo'), 'eM2ja9LE0YE', 'http://wilmax.ru/', '', '');
});
</script>
</div>
</div>
I found posts with similar problem, but solutions in those posts are not working in this case.
Any help would be greatly appreciated.
I would suggest you move to YouTube IFrame Player API:
The IFrame player API lets you embed a YouTube video player on your website and control the player using JavaScript. Unlike the Flash and JavaScript player APIs, which both involve embedding a Flash object on your web page, the IFrame API posts content to an <iframe> tag on your page. This approach provides more flexibility than the previously available APIs since it allows YouTube to serve an HTML5 player rather than a Flash player for mobile devices that do not support Flash.
Flash API and JS API has already been deprecated. I'm not sure if it still work with the current API that is why I suggest you to use Iframe API
Here are some sources that may help you:
JS Fiddle Demo
embedding Flash
Related SO question
Hope this helps!

Embedded Youtube player doesn't exit from full screen

Well, I think this is a major Youtube bug but I don't find any report about it.
I have a web app which is displayed in full screen browser using the JavaScript Fullscreen API.
In the web app there is an embedded Youtube player. When you open the Youtube player in fullscreen, then clicks the Youtube's fullscreen button again to exit the player's fullscreen, it doesn't respond!
I am sure it is related to the fact that the browser is already in full screen mode so there is some kind of conflict.
I have created a simplified example which can be viewed here:
http://run.plnkr.co/CjrrBGBvrSspfa92/
Click the "GO FULLSCREEN" button.
Play the video and click the
fullscreen button. The video will go fullscreen.
Click the
fullscreen button again. It won't exit.
EDIT:
The code for the html file above is here:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<iframe width="560" height="315" src="https://www.youtube.com/embed/b-6B2zyoFsI" frameborder="0" allowfullscreen></iframe>
<button id="btn">GO FULLSCREEN</button>
<script type="text/javascript">
document.getElementById("btn").addEventListener("click", function() {
var elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
});
</script>
</body>
</html>
The thing is I did some searching and it seams Youtube doesn't know if the video is in fullscreen or not when using the JavaScript Fullscreen API nor does Google provide an API call to fo in or out of fullscreen. So, When you click the button and it goes in fullscreen, you'll see the player's fullscreen button not pressed. So, in order to get back to the window view, the user has two options:
1) click on the button 2 times (the first time, the player tries to go in fullscreen and the button changes state, the second time, the player goes in window mode) - this is the solution
2) click Esc on the keyboard.
I checked with the HTML5 player.
Furthermore, I tried injecting a button inside YouTube's iframe so I can select it in order to exit fullscreen, but it didn't work... would have been silly to actually.
This should work:
<div id="videoplayer"></div>
<p><button id="btn">GO FULLSCREEN</button></p>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('videoplayer', {
height: '380',
width: '500',
videoId: 'h7ArUgxtlJs',
fs: 1
});
}
document.getElementById("btn").addEventListener("click", function() {
var elem = document.getElementById('videoplayer');
var requestFullScreen = elem.requestFullscreen || elem.msRequestFullscreen || elem.mozRequestFullScreen || elem.webkitRequestFullscreen;
if (requestFullScreen) {
requestFullScreen.bind(elem)();
}
});
</script>
You can use the classic embed, I belive.
Working demo
This may help: "Exiting Fullscreen Mode":
// Whack fullscreen
function exitFullscreen() {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
// Cancel fullscreen for browsers that support it!
exitFullscreen();
Source.
Side note: Youtube's API is still pretty scarce in terms of what you can customize even in 2015 (due to how it relies on so much iFrame, and they don't want you to reskin their player). You'll likely get to a point where your using a bunch of funky JavaScript hacks to get what you want, which can get messy and unstable. It would be better practice to utilize one of many customizable video players where you can have more control with JS; like JW player, Video.js, Flow player, popcorn.js etc.

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

How to force playing a video in fullscreen?

I need to know how it's possible to force playing a video in fullscreen mode?
Fullscreen is in most of the cases a function by ActionScript and is triggerd with a user action, like mouse click or double click.
The other way is to force playing a video in the mobile devices native player, like youtube does. I have no clue how this approach is realized.
Hope to understand this thing a bit more clearer with your support.
chris
you can tell the Flash stage to go to fullscreen view with this command:
stage.displayState = "fullScreen";
It will work in standalone mode only.
To make it work in the browsers you have to pass the "allowFullScreen" parameter with a "true" value to Flash.
To go fullscreen in mobile devices I believe you have to use the
FSCommand("fullscreen", "true"); method call.
If you are using SWFObject the you can add the allowFullScreen param easily.
SWFObject -2:
<script type="text/javascript">
var so = new SWFObject("movie.swf", "mymovie", "400", "400", "8", "#336699");
so.addParam("wmode", "opaque");
so.addParam("allowScriptAccess", "sameDomain");
so.addParam("allowFullScreen", "true");
so.write("flashcontent");
</script>
SWFObject 2+:
<script type="text/javascript">
var wl = new Object();
wl.flashvars = {};
wl.params = {
allowScriptAccess: "sameDomain",
allowFullScreen: "true",
wmode: "opaque"
};
wl.attributes = {};
swfobject.embedSWF("movie.swf", "flashcontent", "400", "400", "8", "swf/expressInstall.swf", wl.flashvars, wl.params, wl.attributes);
</script>
I hope it helps, good luck
Rob

Categories