Chèn nhạc từ bên ngoài vào file flash bằng ActionScript 3

by 11:08:00 AM 0 nhận xét
Hướng dẫn cách load 1 file nhạc từ bên ngoài vào file flash .swf bằng Action Script 3.0 chỉ với một đoạn script đơn giản.


Bước 1: Tạo file FLA lưu với tên tùy thích, chọn vào keyframe đầu tiên nhấn F9 để mở của sổ soạn thảo ActionScript và dán đoạn code sau vào:
    import flash.events.Event;
    import flash.media.Sound;
    import flash.net.URLRequest;

    var s:Sound = new Sound();
    s.addEventListener(Event.COMPLETE, onSoundLoaded);
    var req:URLRequest = new URLRequest("FileSound.mp3");
    s.load(req);

    function onSoundLoaded(event:Event):void
    {
        var localSound:Sound = event.target as Sound;
        localSound.play();
    }
Bước 2: Đổi đường dẫn FileSound.mp3 trong đoạn script trên thành đường dẫn của file nhạc mà bạn muốn chèn vào. Nhấn Ctrl + Enter để xem kết quả.

Nếu bạn muốn check lỗi load và xem thông tin load thì có thể sử dụng đoạn script sau:
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.media.Sound;
    import flash.net.URLRequest;

    var s:Sound = new Sound();

    s.addEventListener(ProgressEvent.PROGRESS, onLoadProgress);

    s.addEventListener(Event.COMPLETE, onLoadComplete);

    s.addEventListener(IOErrorEvent.IO_ERROR, onIOError);

    var req:URLRequest = new URLRequest("FileSound.mp3");
    s.load(req);

    function onLoadProgress(event:ProgressEvent):void
    {
        var loadedPct:uint = Math.round(100 * (event.bytesLoaded / event.bytesTotal));
        trace("The sound is " + loadedPct + "% loaded.");
    }

    function onLoadComplete(event:Event):void
    {
        var localSound:Sound = event.target as Sound;
        localSound.play();
    }

    function onIOError(event:IOErrorEvent)
    {
        trace("Lỗi trong khi load file: " + event.text);
    }
Tương tự bạn đổi đường dẫn FileSound.mp3 trong đoạn script trên thành đường dẫn của file nhạc mà bạn muốn chèn vào. Nhấn Ctrl + Enter để xem kết quả.

Lưu ý: Thông số load file và lỗi load chỉ hiển thị trong giao diện trace của phần mềm Flash, không hiển trị khi chạy trực tiếp bằng file .swf

Chúc các bạn thành công!

Xem thêm:
- Tạo bộ đếm giờ (Countdown Timer) bằng Action Script 2 trong Flash
- Load hình hoặc movie từ bên ngoài vào một file Flash với Action Script 2
- Load file hình hoặc movie từ bên ngoài vào một file Flash với Action Script 3
- Hướng dẫn gắn link (url) trong Flash Action Script 3
- Cách gọi hàm Javascript từ trong file Flash bằng Action Script 3
Thảo luận

0 nhận xét:

Post a Comment