/
audio-embed.js
61 lines (53 loc) · 1.86 KB
/
audio-embed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
YouTube Audio Embed
--------------------
Original Author: Amit Agarwal
Web: http://www.labnol.org/?p=26740
*/
var audioiFrame;
var audioStarted = false; // Stores whether user turned audio on
// Define function to run when YouTube video is ready
function onYouTubeIframeAPIReady() {
// Add audio icon to webpage
var audioContainer = document.getElementById('audio-container');
var audioIcon = document.createElement('img');
audioIcon.id = 'audio-icon';
audioContainer.appendChild(audioIcon);
// Add audio player to webpage
var audioPlayer = document.createElement('div');
audioPlayer.id = 'audio-player';
audioContainer.appendChild(audioPlayer);
// Change icon to on/off view depending on if video is playing
function audioFunction(playing) {
var image = playing ? 'on.svg' : 'off.svg';
audioIcon.src = 'images/' + image;
}
/* Play or pause video when audio control is clicked and change icon
accordingly */
audioContainer.onclick = function() {
audioiFrame.getPlayerState() === YT.PlayerState.PLAYING || audioiFrame
.getPlayerState() === YT.PlayerState.BUFFERING ? (audioiFrame
.pauseVideo(), audioFunction(!1), audioStarted = false) : (audioiFrame
.playVideo(), audioFunction(!0), audioStarted = true);
}
// Set attributes of embedded audio player
audioiFrame = new YT.Player('audio-player', {
height: '0',
width: '0',
videoId: audioContainer.dataset.video,
playerVars: {
autoplay: audioContainer.dataset.autoplay,
loop: audioContainer.dataset.loop,
start: 1,
},
events: {
onReady: function() {
audioiFrame.setPlaybackQuality('small'),
audioFunction(audioiFrame.getPlayerState() !== YT.PlayerState.CUED);
},
onStateChange: function(audioContainer) {
audioContainer.data === YT.PlayerState.ENDED && audioFunction(!1);
}
}
});
}