星期六, 2月 26, 2011

AS3: 用Flash播放YouTube裡的影片

今天遇到了一個用Flash播放youtube影片的問題,雖然有提供「可能」可以用的網站連結參考,但短時間還是試不出個所以然,所以回家後就google了一下,看看是否有別的方法…結果,還真的有方法!…

其實Google有針對自己的Player提出控制方法,請參考:YouTube ActionScript 3.0 Player API Reference ( http://code.google.com/intl/zh-TW/apis/youtube/flash_api_reference.html )

方法其實非常簡單!只是…不知道的人冤枉路就會走得很久遠…

首先,先找到你的youtube分享連結,例如孫燕姿的新歌:「世說心語」MV完整版,它的分享連結是:http://www.youtube.com/watch?v=pgdgaDdNgwo,「v=」後面就是它的影片ID(video id),也就是「pgdgaDdNgwo」;這個ID很重要,因為我們它關係著我們要播的是哪支影片。

接下來把底下的ActionScript 3.0的語法貼到時間軸裡,並且將紅色的video id取代成你的youtube影片id就OK了:
// The player SWF file on www.youtube.com needs to communicate with your host
// SWF file. Your code must call Security.allowDomain() to allow this
// communication.(設定允許跨網域連到youtube.com)
Security.allowDomain("www.youtube.com");

// This will hold the API player instance once it is initialized.
var player:Object;

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3&video_id=pgdgaDdNgwo")); //換成你的video_id

function onLoaderInit(event:Event):void {
addChild(loader);
loader.content.addEventListener("onReady", onPlayerReady);
loader.content.addEventListener("onError", onPlayerError);
loader.content.addEventListener("onStateChange", onPlayerStateChange);
loader.content.addEventListener("onPlaybackQualityChange",
onVideoPlaybackQualityChange);
}

function onPlayerReady(event:Event):void {
// Event.data contains the event parameter, which is the Player API ID
trace("player ready:", Object(event).data);

// Once this event has been dispatched by the player, we can use
// cueVideoById, loadVideoById, cueVideoByUrl and loadVideoByUrl
// to load a particular YouTube video.
player = loader.content;
// Set appropriate player dimensions for your application
player.setSize(640, 390);//指定影片大小
player.playVideo(); //讓影片立刻播放
}

function onPlayerError(event:Event):void {
// Event.data contains the event parameter, which is the error code
trace("player error:", Object(event).data);
}

function onPlayerStateChange(event:Event):void {
// Event.data contains the event parameter, which is the new player state
trace("player state:", Object(event).data);
}

function onVideoPlaybackQualityChange(event:Event):void {
// Event.data contains the event parameter, which is the new video quality
trace("video quality:", Object(event).data);
}