package geometry.basics { import away3d.core.base.SubGeometry; import away3d.entities.Mesh; import away3d.primitives.Sphere; import flash.events.Event; import flash.geom.Vector3D; import flash.media.Sound; import flash.media.SoundMixer; import flash.utils.ByteArray; import triga.utils.ConvexHull; /** * @author Nicolas Barradeau * http://en.nicoptere.net */ public class H_SoundSPectrum extends BaseScene { [Embed(source = "../../../lib/res/sound/track-film-005.mp3")] //[Embed(source="../../../lib/res/sound/12 nationale 7.mp3")] private var soundSrc:Class; private var sound:Sound = new soundSrc() as Sound; private var subGeometry:SubGeometry; private var origins:Vector.; private var vertices:Vector.; public function H_SoundSPectrum() { setup(); WHITE.lights = lights; var mesh:Mesh = new Sphere( WHITE, 150, 16, 16 ); addMesh( mesh ); //stores a reference to the subgeometry subGeometry = mesh.geometry.subGeometries[ 0 ]; //extracts the vertices and stores a copy vertices = subGeometry.vertexData.concat(); origins = vertices.concat(); //allows the normal vectors to be recomputed automatically ( nicer lights ) subGeometry.autoDeriveVertexNormals = true; //this computes a convex hull of the object subGeometry.updateIndexData( ConvexHull.compute( vertices ) ); addEventListener( Event.ENTER_FRAME, update ); sound.play(); } private function update(e:Event):void { //the byteArray contains 2048 valeurs : 2 channels * 4 integers ( = 1 float 16 bit ) * 256 var ba:ByteArray = new ByteArray(); SoundMixer.computeSpectrum( ba, false ); for (var i:int = 0; i < vertices.length; i+=3 ) { //computes a displacement force with the sound's frequency var f:Number = 250 * ba.readFloat(); //retrieives the original position of the current vertex var o:Vector3D = new Vector3D( origins[ i ], origins[ i + 1 ], origins[ i + 2 ] ); //performs a displacement var d:Vector3D = o.clone(); d.normalize(); d.scaleBy( f ); d = d.add( o ); //updates the vertices positions vertices[ i ] += ( d.x - vertices[ i ] ) * .2; vertices[ i + 1 ] += ( d.y - vertices[ i + 1 ] ) * .2; vertices[ i + 2 ] += ( d.z - vertices[ i + 2 ] ) * .2; } //and updates the vertex buffer of the subgeometry subGeometry.updateVertexData( vertices ); } } }