问题
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