Tải bản đầy đủ (.pdf) (14 trang)

Lap trinh Flash AS 30 lap trinh am thanh

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (537.93 KB, 14 trang )

<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>

<b>AS 3.0 : LẬP TRÌNH VỚI ÂM THANH </b>



( âm thanh ở ñây ñược hiểu theo nghĩa rộng nhất , có thể là một âm hay một file âm thanh)



Việc sử dụng âm thanh thích hợp trong các ứng dụng, game hay web có thể làm tăng thêm những trải nghiệm lý thú


cho người dùng. Trong Flash IDE bạn có thể đưa âm thanh vào thư viện , ñặt âm thanh trên frame của timeline, kèm


âm thanh vào movieclip v..v…Phần này bàn về lập trình actionScript sử dụng lớp Sound và các lớp có liên quan.


Package có liên quan tới âm thanh là flash.media.Sound. Vì vậy phải import package này.



1-Tạo một đối tượng âm thanh và load một âm thanh:


. Tạo một ñối tượng âm thanh :



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

_sound = new Sound( );



-load một 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 trong một package như 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 thanh ta dùng start () và close() .Ví dụ:


_sound = new Sound(new URLRequest("song.mp3"));

_sound.play( );



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


xong mới phát.



ðặt buffer time bằng cách dùng lớp

<i>SoundLoaderContext </i>

( thời gian tính bằng miligiây)


Ví dụ : thiết lập thời gian buffer là 5 s ta dùng lệnh :



</div>
<span class='text_page_counter'>(2)</span><div class='page_container' data-page=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 bài hát bắt đầu từ một vị trí nào đó của file nhạc chứ khơng phải bắt đầu từ đầu ta dùng phương thức:


play(tham số thời gian: miligiây)



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



Ví dụ sau ñây cho phép ñịnh các khoảng thời gian trong một file nhac và lưu nó trong một mảng .Khi cần chơi ñoạn


nào ta ñiền index vào là ñượ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 trong file nhạc ; y là số lần lặp


lại.



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



ðể biết kích thước của file âm thanh ta dùng thuộc tính

<i>bytesTotal</i>

and

<i>bytesLoaded</i>

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ới dung lượng toàn file



package {



</div>
<span class='text_page_counter'>(3)</span><div class='page_container' data-page=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 của máy tính thì sẽ khó nhìn thấy thanh bar lên từ từ, nhưng nếu load file từ internet thì sẽ


thấy ngay như sau đây:



Trong file này có thêm 1 texxtfield và textfield sẽ hiện tỉ lệ % dung lượng file tải về 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(" />8b6130/f/08/f086b23ff9770c5dc0f7304825226155.mp3?filename=Mua-Va-Em-Bang-Kieu.mp3"));
_sound.play( );


</div>
<span class='text_page_counter'>(4)</span><div class='page_container' data-page=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 các thông tin về file âm thanh – ví dụ tên ca sĩ , năm sản xuất…



</div>
<span class='text_page_counter'>(5)</span><div class='page_container' data-page=5>

• artist


• comment



• genre


• songName


• Track


• year



Vis dụ sau ñọc các tag của 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"; }
}


}


</div>
<span class='text_page_counter'>(6)</span><div class='page_container' data-page=6>

ðể biết khi nào file âm thanh kết thúc ta dùng sự kiện lắng nghe

<i>soundComplete </i>



Khi một file âm thanh kết thúc thì đối tượng soundChannel tương ứng phóng ra sự kiện soundComplete . ðiều này


được xác định qua

<i>flash.events.Event.SOUND_COMPLETE</i>

.Khi đó chỉ cần đưa thêm lắng nghe sự kiện này.



Ví dụ: ví dụ này cho phép chơi lần lượt 3 bà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; // bài nhạc hiện tại


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 bài nhạc , load và chơi bài đó


// _playList[_index] chứa tên và ñường dẫn của bài hát tiếp theo


_sound = new Sound( );


</div>
<span class='text_page_counter'>(7)</span><div class='page_container' data-page=7>

// Thêm listener vào channel


_channel.addEventListener(Event.SOUND_COMPLETE,
onComplete);


// tăng biến ñếm lên 1 ñơn vị ñể ñược bài tiếp theo
_index++;


}
}


public function onComplete(event:Event):void
{


playNextSong( );
}



}
}


<b>Tạm dừng và sau ñó chơi tiếp file âm thanh</b>

: Ta dùng các phương thức stop() và 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 một sound và load file âm thanh rồi chạy file đó
_sound = new Sound(new URLRequest("song.mp3"));


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


// Tạo một 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);


}


</div>
<span class='text_page_counter'>(8)</span><div class='page_container' data-page=8>

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


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


}


else {


// Nếu dừng thì restart


_channel = _sound.play(_position);
}


_playing = !_playing;
}


}
}


Lưu ý trong sprite có vẽ thêm các skin . Các skin này ñược ñưa vào nhờ insert symbol, và chonk MovieClip, sau đó


thiết kể một số hình đẻ dùng tween shape . Sau đó đưa vào scene có dùng transform ñể tạo các bản sao



ðo mức âm thanh :



Ta dùng thuộc tính

<i>SoundChannel.leftPeak</i>

and

<i>SoundChannel.rightPeak </i>



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


2 kênh đó khi tải nhạc.



package {


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


</div>
<span class='text_page_counter'>(9)</span><div class='page_container' data-page=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( );



}
}


</div>
<span class='text_page_counter'>(10)</span><div class='page_container' data-page=10>

Sau đây là ví dụ tổng hợp của 2 ví dụ trên. Vừa taọ nút và vừa tạo mức ño âm thanh. Ta tạo nhiều mức đo âm thanh


và đặt nó 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( );



</div>
<span class='text_page_counter'>(11)</span><div class='page_container' data-page=11>

else {


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


_channel = _sound.play(_position);
}


_playing = !_playing;
}


}
}


Tắt tất cả các âm thanh :



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



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


ñây:



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


}


<b>ðọc phổ âm thanh: </b>



Dùng SoundMixer.computeSpectrum( ) ñể lấp ñầy 1 byteArray bằng phổ của âm thanh trong file âm ththanh



ñang chơi trong file .swf



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



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


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


package {


</div>
<span class='text_page_counter'>(12)</span><div class='page_container' data-page=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);
}


}
}


</div>
<span class='text_page_counter'>(13)</span><div class='page_container' data-page=13>

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




Ta tạo một ñối tương SoundTransform : tendoituong(x,y) rồi gắn ñối tượng này vào biến nhận âm thanh chanel ( tức là


channel=sound.play())



Các tham số : x:volume ,từ 0 tới 1


y:balance của âm thanh


Cũng có thể dùng từ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 như sau ñây:



</div>
<span class='text_page_counter'>(14)</span><div class='page_container' data-page=14></div>

<!--links-->

×