import flash.display.Graphics;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLRequest;
const PLOT_HEIGHT:int=200;
const CHANNEL_LENGTH:int=256;
var snd:Sound = new Sound();
var req:URLRequest=new URLRequest("mySound.mp3");//加载声音文件
snd.load(req);
var channel:SoundChannel;
channel=snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
snd.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
var bytes:ByteArray = new ByteArray();
//onEnterFrame() 方法先调用 SoundMixer.computeSpectrum() 方法,后者将声音波形数据存储在 bytes ByteArray 对象中。
function onEnterFrame(event:Event):void {
//通过使用SoundMixer.computeSpectrum()方法,应用程序可以读取当前所播放的波形的原始声音数据。如果当前播放多个SoundChannel对象,SoundMixer.computeSpectrum()方法将显示混合在一起的每个SoundChannel 对象的组合声音数据。
SoundMixer.computeSpectrum(bytes, false, 0);
var g:Graphics=this.graphics;
g.clear();
g.lineStyle(0, 0xFF00CC);
g.beginFill(0x6600CC);
g.moveTo(0, PLOT_HEIGHT);
var n:Number=0;
//for循环将循环访问第一批256个数据值(表示左立体声声道),然后使用Graphics.lineTo()方法绘制一条从每个点到下一个点的直线。第二个for循环将循环访问下一批256个值,此时按相反的顺序(从右到左)对它们进行绘制。
// left channel
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();
// right channel
g.lineStyle(0, 0xCC00FF);
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();
}
function onPlaybackComplete(event:Event) {
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}