This example is a flash AS3.0 example tutorial, in the tutorial we will learn to use the Soundmixer.computespectrum () method to build a simple sound visualization program (that is, wave diagram), hoping to bring help to friends ~ ~
AS3.0 constructs a simple sound visualization program (wave pattern):
Use the Soundmixer.computespectrum () method to display the Sound Wave chart:
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 ("Above the Moon. mp3"); Configure the sound source file address (This is local, can be configured remotely)
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 ();
function Onenterframe (event:event): void
{
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;
//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, 0xcc0066);
G.beginfill (0xcc0066, 0.5);
G.moveto (Channel_length * 2, plot_height);
for (i = channel_length > 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);
}
Load and play a sound file first, and then listen for the Event.enter_frame event that will trigger the Onenterframe () method while playing the sound. The Onenterframe () method first calls the Soundmixer.computespectrum () method, which stores the sound waveform data in the Bytes ByteArray object.
The sound waveform is drawn using the vector drawing API. The For loop iterates through the first 256 data values (representing the left stereo channel), and then uses the Graphics.lineto () method to draw a line from each point to the next point. The second for loop iterates through the next batch of 256 values, drawing them in reverse order (right to left). The generated waveform diagram may produce interesting mirror image effects.