admin管理员组

文章数量:1287648

What I'm trying to do: Create a list of items which contains a link to play audio from a youtube video beside each item

What I'm currently doing: I'm able to do this for a single item using the below:

<div data-video="VIDEO_ID"  
     data-autoplay="0"         
     data-loop="1"             
     id="youtube-audio">
</div>
<script src=""></script>
<script src=".js"></script>

This creates a play button and works perfectly on a single item, however will not work with multiple items on the same page presumably since they all use the same ID. Creating a different ID causes the player to not function. Creating two different data-video's with the same ID will only allow the first one to play, the other will appear correctly but not operate when pressing play.

Looking for solution: Preferably how to use the existing script for multiple videos on the same page. Otherwise an alternative solution for playing audio only on youtube videos with a custom play button would be great.

Thanks!

What I'm trying to do: Create a list of items which contains a link to play audio from a youtube video beside each item

What I'm currently doing: I'm able to do this for a single item using the below:

<div data-video="VIDEO_ID"  
     data-autoplay="0"         
     data-loop="1"             
     id="youtube-audio">
</div>
<script src="https://www.youtube./iframe_api"></script>
<script src="https://cdn.rawgit./labnol/files/master/yt.js"></script>

This creates a play button and works perfectly on a single item, however will not work with multiple items on the same page presumably since they all use the same ID. Creating a different ID causes the player to not function. Creating two different data-video's with the same ID will only allow the first one to play, the other will appear correctly but not operate when pressing play.

Looking for solution: Preferably how to use the existing script for multiple videos on the same page. Otherwise an alternative solution for playing audio only on youtube videos with a custom play button would be great.

Thanks!

Share Improve this question asked Oct 18, 2016 at 21:25 user2372585user2372585 631 gold badge1 silver badge3 bronze badges 2
  • developers.google./youtube/… – StackOverMySoul Commented Oct 18, 2016 at 21:30
  • Check my answer here: stackoverflow./questions/8690255/… – 350D Commented Jul 28, 2017 at 13:42
Add a ment  | 

2 Answers 2

Reset to default 7

If you want you can just copy paste your code like this

https://jsfiddle/8wkjqf3m/

and it works, I'm not sure if you were having a problem doing that or if your problem was elsewhere. It is of course very sloppy looking and the code should be reworked so that you don't have to hard code every function for every video.

I tried to do everything dynamically and failed. I'm not sure if it is possible to dynamically make a function that makes a "new YT.player" for every video id you have and also have the onPlayerReady and onPlayerStateChange functions dynamically made to go with it. I'm sure there is some way but I couldn't figure it out.

The idea though is to make multiple "youtube-audio" divs with different ids for however many youtube players you want to have and have matching multiple "youtube-player" divs for the iframe to function. You can generate that part with javascript if you want so that you don't have to pollute your code with a bunch of repetitive html.

You can make all of your ids dynamically too.

var array = ['put a video id here','put a video id here','put a video id here'];
array = array.map(function(element,index) {
  var div = document.createElement('div');
  div.setAttribute('id', 'youtube-audio-' + index);
  return {'videoId': element, 'div': div };
}

You can just have an array holding the youtube video ids and then initialize all of the divs data-video attributes using

document.getElementById("youtube-audio-1").dataset.video = //youtube video id

I don't see the point in doing all of that dynamically though if there is no way to get around copy pasting x number of "new YT.player"s and "onPlayerReady"s etc...

Good Luck, let me know if I was in the right area or if that was not what you wanted

I have modified the second script so it works as you (or I) want.

To use it use classes instead of IDs. Like the following:

<div data-video="NQKC24th90U" data-autoplay="0" data-loop="1" class="youtube-audio"></div>
<div data-video="KK2smasHg6w" data-autoplay="0" data-loop="1" class="youtube-audio"></div>

Here is the script:

/* 
 YouTube Audio Embed 
 --------------------

 Author: Amit Agarwal
 Web: http://www.labnol/?p=26740

 edited by Anton Chinaev
*/

function onYouTubeIframeAPIReady()
{

    var o= function(e, t) 
    // This function switches the imgs, you may want to change it
    {
        var a=e?"IDzX9gL.png":"quyUPXN.png"; 
        //IDzX9gL is the stopped img and quyUPXN the playing img

        t.setAttribute("src","https://i.imgur./"+a)
        // folder or web direction the img is in. it can be "./"+a
    };

    var counter = 0;
    var bigE = document.querySelectorAll(".youtube-audio");

    bigE.forEach(function(e)
    {
        var t=document.createElement("img");

        t.setAttribute("id","youtube-icon-"+counter),
        t.style.cssText="cursor:pointer;cursor:hand",
        e.appendChild(t);

        var a=document.createElement("div");

        a.setAttribute("id","youtube-player-"+counter),
        e.appendChild(a);

        t.setAttribute("src","https://i.imgur./quyUPXN.png");

        e.onclick=function()
        {
            r.getPlayerState()===YT.PlayerState.PLAYING||r.getPlayerState()===YT.PlayerState.BUFFERING?(r.pauseVideo(),
            o(!1, t)):(r.playVideo(),
            o(!0, t))
        };

        var r= new YT.Player("youtube-player-"+counter,
        {

            height:"0",
            width:"0",
            videoId:e.dataset.video,
            playerVars:
            {
                autoplay:e.dataset.autoplay,loop:e.dataset.loop
            },
            events:
            {
                onReady:function(e)
                {
                    r.setPlaybackQuality("small"),
                    o(r.getPlayerState()!==YT.PlayerState.CUED, t)
                },
                onStateChange:function(e)
                {
                    e.data===YT.PlayerState.ENDED&&o(!1, t)
                }
            }
        })

        counter++;
    });
}

本文标签: How to play audio only from youtube videos using HTML and javascriptStack Overflow