Last active
January 12, 2025 21:58
-
-
Save philcook/cb38130b8649c46f1e9091b490664ab8 to your computer and use it in GitHub Desktop.
Youtube audio only player
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
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
doesn't work on iOS and variable support in android unfortunately. Any ideas for a fix?