Lap trinh Flash AS 30 lap trinh am thanh

14 6 0
Lap trinh Flash AS 30 lap trinh am thanh

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ðể biết kích thước của file âm thanh ta dùng thuộc tính bytesTotal and bytesLoaded của ñối tượng Sound Ví dụ sau sẽ vẽ một thanh ngang mô tả tỉ lệ phần trăm số byte ñược load so v[r]

(1)

AS 3.0 : LẬP TRÌNH VỚI ÂM THANH

( âm ñây ñược hiểu theo nghĩa rộng , âm hay file âm thanh)

Việc sử dụng âm thích hợp ứng dụng, game hay web làm tăng thêm trải nghiệm lý thú cho người dùng Trong Flash IDE bạn ñưa âm vào thư viện , ñặt âm frame timeline, kèm âm vào movieclip v v…Phần bàn lập trình actionScript sử dụng lớp Sound lớp có liên quan Package có liên quan tới âm flash.media.Sound Vì phải import package

1-Tạo ñối tượng âm load âm thanh: Tạo ñối tượng âm :

( tất nhiên phải có dịng lệnh : import flash.media.Sound;) _sound = new Sound( );

-load file âm thanh:

soundFile = new URLRequest("song.mp3"); _sound.load(soundFile);

Hoặc gọn hơn:

_sound.load(new URLRequest("song.mp3"));

Viết lại package sau: package {

import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest;

public class LoadSoundExample extends Sprite { private var _sound:Sound;

public function LoadSoundExample ( ) { _sound = new Sound( );

_sound.load(new URLRequest("song.mp3")); }

} }

ñể bắt ñầu hay dừng âm ta dùng start () close() Ví dụ: _sound = new Sound(new URLRequest("song.mp3")); _sound.play( );

Nếu muốn hát chơi trơn tru chạy chương trình ta nên sử dụng time buffer , hát phải tải xong phát

ðặt buffer time cách dùng lớp SoundLoaderContext ( thời gian tính miligiây) Ví dụ : thiết lập thời gian buffer s ta dùng lệnh :

(2)

var request:URLRequest = new URLRequest("song.mp3");

var buffer:SoundLoaderContext = new SoundLoaderContext(5000); _sound = new Sound(request, buffer);

_sound.play( );

Hay:

var request:URLRequest = new URLRequest("song.mp3");

var buffer:SoundLoaderContext = new SoundLoaderContext(5000); _sound = new Sound( );

_sound.load(request, buffer); _sound.play( );

Nếu muốn hát vị trí file nhạc khơng phải ñầu ta dùng phương thức: play(tham số thời gian: miligiây)

Ví dụ : _sound.play(5500);

Ví dụ sau cho phép định khoảng thời gian file nhac lưu mảng Khi cần chơi ñoạn nào ta ñiền index vào ñược :

package {

import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest;

public class CuePoints extends Sprite { private var _sound:Sound;

private var _cuePoints:Array;

public function CuePoints( ) {

_cuePoints = [0, 10000, 30000, 68000, 120000]; _sound = new Sound(new URLRequest("song.mp3")); // Play from the third cuepoint (30 seconds in) playCuePoint(2);

}

public function playCuePoint(index:int):void { _sound.play(_cuePoints[index]);

} } }

ðể chơi file nhiều lần ta thêm số lần vào phương thức play (x,y) : x:vị trí bắt ñầu chơi file nhạc ; y số lần lặp lại

_sound.play(0, 3); chơi lần từ đầu

ðể biết kích thước file âm ta dùng thuộc tính bytesTotal and bytesLoaded đối tượng Sound Ví dụ sau vẽ ngang mô tả tỉ lệ phần trăm số byte load so với dung lượng tồn file

package {

(3)

import flash.net.URLRequest; import flash.events.Event;

public class ProgressBar extends Sprite { private var _sound:Sound;

public function ProgressBar( ) {

addEventListener(Event.ENTER_FRAME, onEnterFrame); _sound = new Sound(new URLRequest("song.mp3")); _sound.play( );

}

public function onEnterFrame(event:Event):void {

var barWidth:int = 200; var barHeight:int = 5;

var loaded:int = _sound.bytesLoaded; var total:int = _sound.bytesTotal; if(total > 0) {

// Draw a background bar graphics.clear( );

graphics.beginFill(0xFFFFFF);

graphics.drawRect(10, 10, barWidth, barHeight); graphics.endFill( );

// The percent of the sound that has loaded var percent:Number = loaded / total;

// Draw a bar that represents the percent of // the sound that has loaded

graphics.beginFill(0xCCCCCC); graphics.drawRect(10, 10,

barWidth * percent, barHeight); graphics.endFill( );

} } } }

Nếu bạn load file từ ổ đĩa máy tính khó nhìn thấy bar lên từ từ, load file từ internet thấy sau đây:

Trong file có thêm texxtfield textfield tỉ lệ % dung lượng file tải từ internet package { import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest; import flash.events.Event; import flash.text.TextField;

public class ProgressBar1 extends Sprite { private var _sound:Sound;

public function ProgressBar1( ) {

addEventListener(Event.ENTER_FRAME, onEnterFrame); _sound = new Sound(new

URLRequest("http://dl.mp3.zdn.vn/fsfsdfdsfdserwrwq3/0b0237487f954a4536f28f029a75488e/4c 8b6130/f/08/f086b23ff9770c5dc0f7304825226155.mp3?filename=Mua-Va-Em-Bang-Kieu.mp3")); _sound.play( );

(4)

public function onEnterFrame(event:Event):void {

var barWidth:int = 200; var barHeight:int = 5;

var loaded:int = _sound.bytesLoaded; var total:int = _sound.bytesTotal; if(total > 0) {

// Draw a background bar graphics.clear( );

graphics.beginFill(0xFffFFF);

graphics.drawRect(10, 10, barWidth, barHeight); graphics.endFill( );

// The percent of the sound that has loaded var percent:Number = loaded / total;

// Draw a bar that represents the percent of // the sound that has loaded

graphics.beginFill(0xC12111); graphics.drawRect(10, 10,

barWidth * percent, barHeight); graphics.endFill( );

t1.text=(Math.round(100*percent)).toString()+"%" ; }

} } }

ðọc thông tin file âm – ví dụ tên ca sĩ , năm sản xuất…

(5)

• artist • comment • genre • songName • Track • year

Vis dụ sau ñọc tag file nhạc mp3 package {

import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest; import flash.events.Event; import flash.text.*;

public class ID3Reader extends Sprite { private var _sound:Sound;

public function ID3Reader ( ) {

_sound = new Sound(new URLRequest("song.mp3")); _sound.addEventListener(Event.ID3, onID3); _sound.play( );

}

public function onID3(event:Event):void { // Create a text field and display it

var id3Display:TextField = new TextField( ); id3Display.backgroundColor=0xC7F755;

addChild(id3Display); id3Display.x = 10; id3Display.y = 20; id3Display.width = 200; id3Display.height = 200; id3Display.background = true; id3Display.multiline = true; id3Display.wordWrap = true;

// Add some info about the song to the text field

id3Display.text += " ten bai hat : "+_sound.id3.songName + "\n"; id3Display.text += " ten ca si : "+_sound.id3.artist + "\n"; id3Display.text += " Album : "+_sound.id3.album + "\n";

id3Display.text += "Nam san xuat : "+_sound.id3.year + "\n"; } }

}

(6)

ðể biết file âm kết thúc ta dùng kiện lắng nghe soundComplete

Khi file âm kết thúc đối tượng soundChannel tương ứng phóng kiện soundComplete ðiều được xác định qua flash.events.Event.SOUND_COMPLETE.Khi cần đưa thêm lắng nghe kiện Ví dụ: ví dụ cho phép chơi hát song1.mp3,song2.mp3.song3.mp3

package {

import flash.display.Sprite; import flash.media.Sound; import flash.net.URLRequest; import flash.events.Event;

import flash.media.SoundChannel;

public class PlayList extends Sprite { private var _sound:Sound;

private var _channel:SoundChannel;

private var _playList:Array; // mảng chứa danh sách nhạc private var _index:int = 0; // nhạc

public function PlayList( ) { // tạo danh sách nhạc _playList = ["song1.mp3", "song2.mp3", "song3.mp3"]; playNextSong( );

}

private function playNextSong( ):void {

// If there are still songs in the playlist if(_index < _playList.length) {

// Tạo nhạc , load chơi

// _playList[_index] chứa tên ñường dẫn hát

_sound = new Sound( );

(7)

// Thêm listener vào channel

_channel.addEventListener(Event.SOUND_COMPLETE, onComplete);

// tăng biến ñếm lên ñơn vị ñể ñược _index++;

} }

public function onComplete(event:Event):void {

playNextSong( ); }

} }

Tạm dừng sau chơi tiếp file âm thanh : Ta dùng phương thức stop() play() Lưu ý không dùng lệnh close()

package {

import flash.display.Sprite; import flash.media.Sound;

import flash.media.SoundChannel; import flash.net.URLRequest; import flash.events.Event; import flash.display.Sprite; import flash.events.MouseEvent;

public class PlayPause extends Sprite { private var _sound:Sound;

private var _channel:SoundChannel; private var _playPauseButton:Sprite; private var _playing:Boolean = false; private var _position:int;

public function PlayPause( ) {

// tạo sound load file âm chạy file _sound = new Sound(new URLRequest("song.mp3"));

_channel = _sound.play( ); _playing = true;

// Tạo Sprite ñể dùng button _playPauseButton = new Sprite( ); addChild(_playPauseButton);

_playPauseButton.x = 10; _playPauseButton.y = 20;

_playPauseButton.graphics.beginFill(0xffcccc);

_playPauseButton.graphics.drawRoundRect(0, 0, 20, 40,10); _playPauseButton.addEventListener(MouseEvent.MOUSE_UP, onPlayPause);

}

(8)

// Nếu chạy dừng lại ghi nhớ vị trí dừng if(_playing) {

_position = _channel.position; _channel.stop( );

} else {

// Nếu dừng restart

_channel = _sound.play(_position); }

_playing = !_playing; }

} }

Lưu ý sprite có vẽ thêm skin Các skin ñược ñưa vào nhờ insert symbol, chonk MovieClip, sau thiết kể số hình ñẻ dùng tween shape Sau ñó ñưa vào scene có dùng transform để tạo

ðo mức âm :

Ta dùng thuộc tính SoundChannel.leftPeak and SoundChannel.rightPeak

Mỗi âm có kênh phải trái với biên ñộ khác , ví dụ sau ta tạo mơ tả độ mạnh yếu 2 kênh tải nhạc

package {

import flash.display.Sprite; import flash.media.Sound;

(9)

public class SoundLevels extends Sprite { private var _sound:Sound;

private var _channel:SoundChannel;

public function SoundLevels( ) {

addEventListener(Event.ENTER_FRAME, onEnterFrame); _sound = new Sound(new URLRequest("song.mp3")); _channel = _sound.play( );

}

public function onEnterFrame(event:Event):void {

var leftLevel:Number = _channel.leftPeak * 100; var rightLevel:Number = _channel.rightPeak * 100; graphics.clear( );

graphics.beginFill(0xcccccc);

graphics.drawRect(10, 10, leftLevel, 10); graphics.endFill( );

graphics.beginFill(0xcccccc);

graphics.drawRect(10, 25, rightLevel, 10); graphics.endFill( );

} }

(10)

Sau ví dụ tổng hợp ví dụ Vừa taọ nút vừa tạo mức ño âm Ta tạo nhiều mức ño âm và đặt theo chiều đứng

package { import flash.display.Sprite; import flash.media.Sound; import flash.media.SoundChannel; import flash.net.URLRequest; import flash.events.Event; import flash.events.MouseEvent;

public class SoundLevels extends Sprite { private var _sound:Sound;

private var _channel:SoundChannel;

private var _playing:Boolean = true; private var _position:int;

private var _playPauseButton = new Sprite( );

public function SoundLevels( ) {

addEventListener(Event.ENTER_FRAME, onEnterFrame); _sound = new Sound(new URLRequest("song.mp3")); _channel = _sound.play( );

_playPauseButton = new Sprite( ); addChild(_playPauseButton);

_playPauseButton.x = 10; _playPauseButton.y = 20;

_playPauseButton.graphics.beginFill(0xffcccc); _playPauseButton.graphics.drawRect(0, 0, 20, 20);

_playPauseButton.addEventListener(MouseEvent.MOUSE_UP,onPlayPause); }

public function onEnterFrame(event:Event):void {

var leftLevel:Number = _channel.leftPeak * 100; var rightLevel:Number = _channel.rightPeak * 100; graphics.clear( );

graphics.beginFill(0xcccccc);

graphics.drawRect(10, 200, 10,-leftLevel); graphics.endFill( );

graphics.beginFill(0xcccccc);

graphics.drawRect(30, 200, 10,-rightLevel); graphics.endFill( );

graphics.beginFill(0xcccccc);

graphics.drawRect(50, 200, 10,-leftLevel-20*Math.random()); graphics.endFill( );

graphics.beginFill(0xcccccc);

graphics.drawRect(70, 200, 10,-leftLevel-20*Math.random()); graphics.endFill( );

graphics.beginFill(0xcccccc);

graphics.drawRect(90, 200, 10,-leftLevel-20*Math.random()); graphics.endFill( );

}

public function onPlayPause(event:MouseEvent):void { // If playing, stop Take note of position

if(_playing) {

_position = _channel.position; _channel.stop( );

(11)

else {

// If not playing, re-start it at // last known position

_channel = _sound.play(_position); }

_playing = !_playing; }

} }

Tắt tất âm :

Ta dùng stopAll() ñối tượng soundMixer

Trong thực tế ta thường thêm event handler vào nút để kích gọi tới hàm có chứa lệnh stopAll() sau ñây:

public function stopSounds(event:Event):void { SoundMixer.stopAll( );

}

ðọc phổ âm thanh:

Dùng SoundMixer.computeSpectrum( ) ñể lấp ñầy byteArray phổ âm file âm ththanh ñang chơi file swf

Lưu ý phần import phải có

flash.media.Sound;flash.media.SoundChannel;flash.media.SoundMixer;flash.utils.ByteArray ;

Code sau ñây cho phổ âm dạng ñồ thị với khaongr tần số lấy tuỳ ý package {

(12)

import flash.media.SoundChannel; import flash.media.SoundMixer; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.text.TextField;

public class SoundMixer_computeSpectrumExample extends Sprite { public function SoundMixer_computeSpectrumExample() {

var snd:Sound = new Sound();

var req:URLRequest = new URLRequest("song.mp3"); snd.load(req);

var channel:SoundChannel; channel = snd.play();

addEventListener(Event.ENTER_FRAME, onEnterFrame);

channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete); }

private function onEnterFrame(event:Event):void { var bytes:ByteArray = new ByteArray();

const PLOT_HEIGHT:int = 350; const CHANNEL_LENGTH:int = 256;

SoundMixer.computeSpectrum(bytes, false, 0);

var g:Graphics = this.graphics; g.clear(); g.lineStyle(0, 0x6600CC); g.beginFill(0x6600CC); g.moveTo(0, PLOT_HEIGHT);

var n:Number = 0;

for (var i:int = 0; i < CHANNEL_LENGTH; i++) { n = (bytes.readFloat() * PLOT_HEIGHT); g.lineTo(i * 2, PLOT_HEIGHT - n); }

g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT); g.endFill();

g.lineStyle(0, 0xCC0066); g.beginFill(0xCC0066, 0.5);

g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);

for (i = CHANNEL_LENGTH; i > 0; i ) { n = (bytes.readFloat() * PLOT_HEIGHT); g.lineTo(i * 2, PLOT_HEIGHT - n); } g.lineTo(0, PLOT_HEIGHT); g.endFill(); }

private function onPlaybackComplete(event:Event):void { removeEventListener(Event.ENTER_FRAME, onEnterFrame); }

} }

(13)

Thiết lập volume balance cho âm ( ñịnh số lượng âm loa phải , trái) :

Ta tạo ñối tương SoundTransform : tendoituong(x,y) gắn ñối tượng vào biến nhận âm chanel ( tức channel=sound.play())

Các tham số : x:volume ,từ tới y:balance âm Cũng dùng tham số riêng Ví dụ :

import flash.display.Sprite; import flash.media.Sound;

import flash.media.SoundChannel; import flash.media.SoundMixer; import flash.net.URLRequest;

var _sound:Sound = new Sound(new URLRequest("song.mp3")); var channel:SoundChannel = _sound.play( );

var transform1:SoundTransform = new SoundTransform(); transform1.volume = 0.8;

transform1.pan = -1.0;

channel.soundTransform = transform1; hoặc dùng tham số chung sau ñây:

(14)

Ngày đăng: 23/04/2021, 21:02

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan