autoplay youtube video

坚强是说给别人听的谎言 提交于 2020-01-25 18:52:13

问题


i have a site and in the home page i have an embedded youtube video, the div that is containing the player is initially hidden(display:none), so, when a button(video) is clicked, i hide the content of the page and show the youtube player, all works ok, but i would love that when the button(video) is clicked, the player shows up and start to reproduce the video automatically, but i've faild in each attempt, i'm using a code that i find in other web and made some changes

swfobject.addLoadEvent( ytplayer_render_player );
function ytplayer_render_player( )
{
swfobject.embedSWF
(
  'http://www.youtube.com/v/' + youtube_uhma.home + '&enablejsapi=1&rel=0&fs=1&playerapiid=ytplayer',
  'ytplayer_div1',
  '425',
  '344',
  '8',
  null,
  null,
  {
    allowScriptAccess: 'always',
    allowFullScreen: 'true'
  },
  {
    id: 'ytplayer_object'
  }
);
}  
 function onYouTubePlayerReady( playerid )
 {
    var o = document.getElementById( 'ytplayer_object' );
    if ( o )
    {
      o.addEventListener( "onStateChange", "ytplayer_statechange" );
      o.addEventListener( "onError", "ytplayer_error" );
    }
}
 function ytplayer_statechange( state )
 {
    if ( state == 0 )
    {
      ytplayer_playlazy( 5000 );
   }
 }

function ytplayer_error( error )
{
  if ( error )
  {
    ytplayer_playlazy( 5000 );
  }
 }

function ytplayer_playlazy( delay )
{
    if ( typeof ytplayer_playlazy.timeoutid != 'undefined' )
    {
      window.clearTimeout( ytplayer_playlazy.timeoutid );
    }
    ytplayer_playlazy.timeoutid = window.setTimeout( ytplayer_play, delay );
}
function ytplayer_play( )
{
  var o = document.getElementById( 'ytplayer_object' );
  if ( o )
  {
    o.loadVideoById( youtube_uhma.home );
  }
}

i've post the entire code i'm using, so, how can i make autoplay here, you can see my web in action here Uhma
thanks to all


回答1:


well, after reading the API reference of the Youtube JavaScript player and coding for some while, this worked for me:

in the ytplayer_statechange function, I changed the validation of the state to

if ( state == 5 ) //5 means that is ready to play
{
    ytplayer_playlazy( 1000 );
}

The video started to play after 1 sec. I don't know if this is the best way but it is enough for me.



来源:https://stackoverflow.com/questions/5097686/autoplay-youtube-video

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!