In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

JSON形式で読み込まれたYoutube動画ID使って動画連続再生

/**
 * Copyright siouxcitizen ( http://wonderfl.net/user/siouxcitizen )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/jBt4
 */

// forked from fumix's youtube api
/**
 * JSON形式で読み込まれたYoutube動画ID使って動画連続再生
 * 
 * Fork元からそのまま使用している背景サムネイルとは特に連携(クリックして再生動画指定とか)してません。。。
 * 背景サムネイルが見れるようにZボタンでPlayerをごまかし的に非表示にします(最初にPlayerか背景のどこかのクリック必要)
 * 
 * 参考コード
 * youtube api(今回Forkさせて頂いたコードです)
 * http://wonderfl.net/c/axrB
 * Youtube動画を連続再生できるか試してみました(前に作った自分のコードです)
 * http://wonderfl.net/c/dpQt
 */
package {
    import com.adobe.serialization.json.JSON;

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    /**
     * @author fumix
     */
    [SWF(backgroundColor="#FFFFFF", frameRate="31", width="465", height="465")]
    public class TestYoutube extends Sprite {
        private const APIURL : String = 'http://gdata.youtube.com/feeds/api/videos?start-index=1&max-results=50&orderby=viewCount&alt=json&vq=';
        private const KEYWORD : String = 'AKB48';
        private var _w : int;
        private var _h : int;
        private var _jsonObject : Object;
        public var _bollon : Balloon;
        private var _base : Sprite;

        private const YOUTUBE_PLAYER_URL : String = "http://www.youtube.com/v/lkHlnWFnA0c?version=3"; //公式ヘビーローテーションがデフォルト再生の1曲目に設定されてます
        private var _loader : Loader;
        private var _player : Object;
        private var _movieIdListIndex : int = 0;
        private var _movieIdList : Array = new Array();
        private var _isPlayerDisp : Boolean = true ;
        public function TestYoutube() {
            if (stage) initialize();
            else addEventListener(Event.ADDED_TO_STAGE, initialize);
        }

        private function initialize(event : Event = null) : void {
            removeEventListener(Event.ADDED_TO_STAGE, initialize);
            // ステージ設定
            // stage.quality = StageQuality.LOW;
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            // 背景設定
            _w = stage.stageWidth;
            _h = stage.stageHeight;
            var bmd : BitmapData = new BitmapData(_w, _h, false, 0xFFFFFF);
            addChild(new Bitmap(bmd));
            //ベース
            _base = new Sprite();
            addChild(_base);
            //吹き出し
            _bollon = new Balloon(0, 0, _w, _h);
            addChild(_bollon);
            
            // youtubeから検索結果のjsonをロード
            var urlLoader : URLLoader = new URLLoader();
            urlLoader.addEventListener(Event.COMPLETE, urlLoadCompleteHandler);
            urlLoader.load(new URLRequest(APIURL + KEYWORD));

            //Youtube Playerを取得して動画を再生
            _loader = addChild(new Loader()) as Loader;
            _loader.contentLoaderInfo.addEventListener(Event.INIT, youtubePlayerLoadCompleteHandler, false, 0, true);
            //_urlLoader.addEventListener(Event.COMPLETE, youtubePlayerLoadCompleteHandler);
            _loader.x = 60;
            _loader.y = 50;
            _loader.load(new URLRequest(YOUTUBE_PLAYER_URL));

            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);    //イベントリスナーの登録
        }

        private function urlLoadCompleteHandler(event : Event) : void {
            // jsonデータをobjectに
            _jsonObject = JSON.decode(event.currentTarget.data);
            for (var i : String in _jsonObject['feed']['entry']) {
                var movieId : String = String(_jsonObject['feed']['entry'][i]['id']['$t']).replace('http://gdata.youtube.com/feeds/api/videos/', '');
                _movieIdList.push(movieId);
                var url : String = "http://www.youtube.com/watch?v=" + movieId;                
                //var url : String = "http://www.youtube.com/watch?v=" + String(_jsonObject['feed']['entry'][i]['id']['$t']).replace('http://gdata.youtube.com/feeds/api/videos/', '');

                var thumbURL : String = _jsonObject['feed']['entry'][i]['media$group']['media$thumbnail'][0]['url'];
                var title : String = _jsonObject['feed']['entry'][i]['title']['$t'];
                var thum : ThumbImage = new ThumbImage(thumbURL, url, title);
                var c : int = Math.ceil(_w / 134);
                var cy : int = int(i) / c;
                var cx : int = int(i) - cy * c;
                var dx : Number = 134 * cx;
                var dy : Number = 101 * cy;
                thum.x = dx;
                thum.y = dy;
                _base.addChild(thum);
            }
        }

        private function youtubePlayerLoadCompleteHandler(event : Event) : void {
            _loader.content.addEventListener("onReady", onPlayerReady);
            _loader.content.addEventListener("onError", onPlayerError);
            _loader.content.addEventListener("onStateChange", onPlayerStateChange);
            _loader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
        }

        private function onPlayerReady(event:Event):void {
            _player = _loader.content;

            _player.setSize(352, 230);

            if (_movieIdList.lenght < 1) _player.loadVideoById("lkHlnWFnA0c", 0, "default"); //動画IDを何も取得できなかった場合は公式ヘビーローテーションを再生します
            _player.loadVideoById(_movieIdList[_movieIdListIndex], 0, "default"); //1曲目再生
        }
        
        private function onPlayerError(event:Event):void {
            // Event.data contains the event parameter, which is the error code
        }
        
        private function onPlayerStateChange(event:Event):void {
            // Event.data contains the event parameter, which is the new player state
            //プレイヤーの状態を判定
            //未開始(-1)、終了(0)、再生中(1)、一時停止中(2)、バッファリング中(3)、頭出し済み(5)
            if (Object(event).data == "0") { //動画が終了した場合
                _movieIdListIndex++;
                if(_movieIdListIndex > _movieIdList.length - 1) return; //動画IDリストを超えた場合は処理を行わない
                _player.loadVideoById(_movieIdList[_movieIdListIndex], 0, "default");
            }
        }
        
        private function onVideoPlaybackQualityChange(event:Event):void {
            // Event.data contains the event parameter, which is the new video quality
        }

        // → OR zボタン押下時にごまかし気味にYoutube Playerを隠します。
        private function onKeyDown(event:KeyboardEvent):void {
            switch(event.keyCode) {
                case 39: case 90:    //→ z
                    if (_isPlayerDisp) {
                        _loader.x = 60;
                        _loader.y = 50;
                        _player.setSize(352, 230);
                        _isPlayerDisp = false;
                    } else {
                        _loader.x = 550;
                        _loader.y = 550;
                        _player.setSize(1, 1);
                        _isPlayerDisp = true;
                    }
            }
        }

    }
}
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.LoaderContext;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;

class ThumbImage extends Sprite {
    private var _img : String;
    private var _url : String;
    private var _title : String;

    public function ThumbImage(imageURL : String, youtubeURL : String, title : String) {
        _img = imageURL;
        _url = youtubeURL;
        _title = title;
        buttonMode = true;
        if (stage) initialize();
        else addEventListener(Event.ADDED_TO_STAGE, initialize);
    }

    private function initialize(event : Event = null) : void {
        removeEventListener(Event.ADDED_TO_STAGE, initialize);
        // 画像のロード
        var loader : Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadCompleteHandler);
        loader.load(new URLRequest(_img), new LoaderContext(true));
        // マウスハンドラ
        addEventListener(MouseEvent.CLICK, onMouseClick);
        addEventListener(MouseEvent.ROLL_OVER, onRollOver);
        addEventListener(MouseEvent.ROLL_OUT, onRollOut);
    }

    private function onRollOut(event : MouseEvent) : void {
        var t:TestYoutube = this.parent.parent as TestYoutube;
        t._bollon.hide();
    }

    private function onRollOver(event : MouseEvent) : void {
        var t:TestYoutube = this.parent.parent as TestYoutube;
        t._bollon.show(_title);
    }

    private function onMouseClick(event : MouseEvent) : void {
        navigateToURL(new URLRequest(_url), '_blank');
    }

    private function loadCompleteHandler(event : Event) : void {
        var bm : Bitmap = event.target.loader.content as Bitmap;
        var scale : Number = 100 / bm.height;
        bm.height = 100;
        bm.scaleX = scale;
        bm.smoothing = true;
        addChild(bm);
    }
}
class Balloon extends Sprite {
    private var _tl : TextField;
    private var _top : int;
    private var _left : int;
    private var _right : int;
    private var _bottom : int;
    private var _sp : Sprite;

    public function Balloon(top : int, left : int, right : int, bottom : int) {
        _sp = new Sprite();
        _sp.graphics.lineStyle(0.1, 0xFFFFFF);
        _sp.graphics.beginFill(0x000000);
        _sp.graphics.drawRect(0, 0, 124, 20);
        _sp.graphics.endFill();
        addChild(_sp);
        _tl = new TextField();
        _tl.wordWrap = true;
        _tl.autoSize = TextFieldAutoSize.LEFT;
        _tl.width = 180;
        _tl.textColor = 0xFFFFFF;
        _tl.x = _tl.y = 2;
        addChild(_tl);

        _top = top;
        _left = left;
        _right = right;
        _bottom = bottom;
        visible = false;
        mouseEnabled = false;
        mouseChildren = false;
    }

    public function show(text : String) : void {
        _tl.text = text;
        _sp.width = _tl.width + 4;
        _sp.height = _tl.textHeight + 8;
        visible = true;
        addEventListener(Event.ENTER_FRAME, enterFrameHandler);
    }

    public function hide() : void {
        removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
        visible = false;
    }

    private function enterFrameHandler(event : Event) : void {
        x = stage.mouseX + 5;
        y = stage.mouseY + 5;
        if (x > _right - width) x = x - width - 5;
        if (y > _bottom - height) y = y - height - 5;
    }
}