If my video has English subtitles, I can force to show them with a code like:
hl=en&cc_lang_pref=en&cc_load_policy=1
So the full code would be:
<iframe
width="560" height="315"
src="https://www.youtube.com/embed/3I3Rjw_4Ucw?hl=en&cc_lang_pref=en&cc_load_policy=1"
frameborder="0" gesture="media"
allow="encrypted-media" allowfullscreen>
</iframe>
However, it does not seem to work if the video has not subtitles. I want to force to show the auto-generated subtitles from Youtube in that case. Is it possible?
There is no official or documented way to force auto-generated captions in embedded videos. However there is a solution with the setOption method which works now, but there is no guarantee it will work in the future as this is a non documented call of the method:
<iframe id="existing-iframe"
width="640" height="360"
src="https://www.youtube.com/embed/q2C0EO0zzAY?enablejsapi=1&cc_load_policy=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let player
const onApiChange = _ => {
if (typeof player.setOption === 'function') {
player.setOption('captions', 'track', {languageCode: 'en'}) // undocumented call
}
}
function onYouTubeIframeAPIReady() {
player = new YT.Player('existing-iframe', {events: {onApiChange}})
}
</script>
See this code working in this jsFiddle.
You have to wait for an onApiChange event before using the setOption function. (See: https://developers.google.com/youtube/iframe_api_reference#Events) According to the docs only the 'fontSize' and the 'reload' parameters are supported. However, changing the captions track works too and it turns ON the captions as a side-effect. I tried only the 'en' languageCode, of course this will change to the normal english captions track if there is one available, but will display the auto-generated english captions in the absence of a predefined track.
(You can also query the active captions track with the getOption method, but it will return nothing if the auto-generated captions are used.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With