I am working on a webpage that uses JavaScript to embed a YouTube video with multiple language audio tracks (MLA) and subtitles. My example video ID is PWirijQkH4M
. I want to allow users to switch audio tracks with one button and switch subtitles with another button.
I have implemented the following code, but it does not seem to work as expected. The video does not switch tracks when the buttons are clicked. How can I achieve this functionality?
Any guidance on how to correctly implement the audio and subtitle track switching functionality would be greatly appreciated. Thank you!
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YouTube Multi-language Audio and Subtitle Switching</title>
<script src="https://www.youtube.com/iframe_api"></script>
<style>
/* Button styles */
.button {
display: inline-block;
padding: 5px 10px;
margin: 5px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
.button:hover {
background-color: #3e8e41;
}
</style>
</head>
<body>
<div id="player"></div>
<button class="button" id="audioTrackButton">Switch Audio Track</button>
<button class="button" id="subtitleTrackButton">Switch Subtitles</button>
<script>
// Prepare YouTube player
var player;
var videoId = 'PWirijQkH4M'; // Example video ID
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: videoId,
events: {
'onReady': onPlayerReady,
}
});
};
// Triggered when player is ready
function onPlayerReady() {
// Check if the video supports multiple audio tracks and subtitles
if (player.tracks.length > 1) {
// Initialize audio and subtitle track indexes
var currentAudioTrackIndex = 0;
var currentSubtitleTrackIndex = 0;
// Event handler for switching audio track button
document.getElementById('audioTrackButton').addEventListener('click', function() {
currentAudioTrackIndex = (currentAudioTrackIndex + 1) % player.tracks.length;
player.tracks[currentAudioTrackIndex].languageCode.select();
});
// Event handler for switching subtitles button
document.getElementById('subtitleTrackButton').addEventListener('click', function() {
currentSubtitleTrackIndex = (currentSubtitleTrackIndex + 1) % player.tracks.length;
player.tracks[currentSubtitleTrackIndex].languageCode.select();
});
} else {
console.warn('The video does not support multiple audio tracks or subtitles');
}
}
</script>
</body>
</html>