Skip to content

Instantly share code, notes, and snippets.

@philcook
Last active January 30, 2023 19:39
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philcook/cb38130b8649c46f1e9091b490664ab8 to your computer and use it in GitHub Desktop.
Save philcook/cb38130b8649c46f1e9091b490664ab8 to your computer and use it in GitHub Desktop.
Youtube audio only player
<!DOCTYPE html>
<div style="display:flex;justify-content:center;align-items:center;">
<div style="width:400px;height:300px;">
<div data-video="I_2D8Eo15wE" data-autoplay="0" data-loop="1" id="youtube-audio"></div>
<div style="clear:both;margin:10px;text-align:center">
</div>
</div>
</div>
<script type="text/javascript" src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
var ctrlq = document.getElementById("youtube-audio");
ctrlq.innerHTML = '<img id="youtube-icon" src=""/><div id="youtube-player"></div>';
ctrlq.style.cssText = 'width:150px;margin:2em auto;cursor:pointer;cursor:hand;display:none';
ctrlq.onclick = toggleAudio;
player = new YT.Player('youtube-player', {
height: '0',
width: '0',
videoId: ctrlq.dataset.video,
playerVars: {
autoplay: ctrlq.dataset.autoplay,
loop: ctrlq.dataset.loop,
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function togglePlayButton(play) {
document.getElementById("youtube-icon").src = play ? "https://i.imgur.com/IDzX9gL.png" : "https://i.imgur.com/quyUPXN.png";
}
function toggleAudio() {
if ( player.getPlayerState() == 1 || player.getPlayerState() == 3 ) {
player.pauseVideo();
togglePlayButton(false);
} else {
player.playVideo();
togglePlayButton(true);
}
}
function onPlayerReady(event) {
player.setPlaybackQuality("small");
document.getElementById("youtube-audio").style.display = "block";
togglePlayButton(player.getPlayerState() !== 5);
}
function onPlayerStateChange(event) {
if (event.data === 0) {
togglePlayButton(false);
}
}
</script>
@drjamesj
Copy link

doesn't work on iOS and variable support in android unfortunately. Any ideas for a fix?

@gitbucket-crypto
Copy link

How to start and stop the video using js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment