Add

Making Things + AS3 – Part 1 and 2 LED Sound Visualizer


In the obnoxious spirit of having a ton of "Part 1″ posts going on here, I decided to put up this initial experiment with my new making things controller. There's a lot to cover as this has become one of the more challenging things I have been tinkering with lately. Before going any further let me give you a brief introduction to what this is. If you are familiar with Making Things and flosc then skip to the next paragraph. The fine folks at Making Things have made a hardware controller kit that is capable of interfacing with the Flash environment. Basically what this means is that you can interact with a swf electronically and mechanically using this hardware interface. Things like stepper and servo motors, proximity sensors, and other electronic devices can be controlled and monitored through flash. Flash is able to do this by way of a java server application that is run in the background called flosc. It's based on the system of OSC that is typically used to interface MIDI applications and hardware. You can learn about OSC here and you can read more about flosc here.

Also before going any further I highly recommend you read through John Barton's progress before proceeding with this post as he has provided the insight and basis for this experiment and has gone through a few more trials and tribulations over this then myself. Check out his blog here. Make sure you go through all his posts first as there is a progression and you will have a good sense of where things stand.

That being said, AS3 integration of the controller seems to be a relatively new thing. I know John, as you saw in his posts, hit some snags with the communication of data and flosc. I know I came across issues on my own trying to get his examples working but hopefully this will be one more resource to help get something going. Just so you know, the code used to communicate with flosc is in "beta" version if you will. John mentioned planning on updating the code per the recent developments he encountered in his latest post. Since he's a busy man like the rest of us, I tried making a couple modifications myself in the meantime. Ideally it would be great to do a re-write using the Binary Socket class in AS3.

I have included what seems to be the most recent version of flosc in the source files. I reccomend you check on the version and with John's progress as well. Be patient and prepared for frustration as there are a lot of elements in this scenario that can create issues and make things NOT work.

Before starting up flosc you will need to disable your internet settings. I hope to have an example of the controller working within a network even a utility class that can configure the controller in a network using DHCP, but for the time being… Go to your system preferences. Make sure both the ethernet and the usb connection are plugged into the computer (I have the external power supply connected to mine). You might get a message saying that the Network has detected the Making Things etc.. click ok and enable that along with your ethernet port. That message simply indicates that the computer can connect to the board via the USB cable. Because the board only communicates via ethernet, the USB is only important for powering the board and using mchelper.

At this point you could fire up the mchelper application that I included with the source. Be sure to check the version of this on the making things site. Test if the board is connected by clicking on the Ethernet tab and in the command line type in "/appled/0/state 1″ and click send. Hopfully your number 0 LED will light up! Make sure you quit the mchelper program as it will block connections made using flosc.

Next we need to start up the flosc server application. First, make note of your computers IP address as you will need it in the class source. To start flosc using a mac:
Open up the terminal. Type "cd " (be sure to include the space after cd)
Then drag the flosc folder into the terminal window. This will paste the path into the terminal window.
Hit return and you should be in the flosc directory.
Type "java Gateway 10000 10000″ and you should see "OscServer created…" and "TcpServer created…"
This will tell you that the flosc server is running. Gateway is the java program in the flosc directory and the 10000 numbers designate the incoming and outgoing ports respectively that flosc and the board talk to each other on.

Next open up the MakeLEDTest.fla and the MakeMusicLED.as file. In the class file you will see const variables for the computer and controller IP address you should really only need to add the computers IP address. Publish the file and hopefully you will see a successful connection in the output/debugger window. If you do, click on the green button and the music should be playing along with the LEDs on the controller and the visual representation in the swf. If they don't, don't fret. It took me quite a while to get things working. I noticed things as silly as adding a private class variable to the as file would prevent the LED's from working. Retrace your steps and check the data flow. Make sure the IP addresses match up.


Before getting to the LED code, be aware that I have made a couple minor changes to the OSCConnection.as file that John did. I added two private methods to reorder the OSC attributes in the XML data in regards to Johns discoveries. I also changed the type to "i" instead of "s" and things worked well. I'm sure this is a band-aid fix for the time being.

So now for the code actual LED code. Here we are going to load a mp3 and have the LED's on the board reflect the amplitude level of the music. Check out Lee Brimelow's example here for a refresher on getting the amplitude value of a sound channel. The only change I made is averaging the two channels since we have one set of LED's on the board.

Here's the code:

package com.hydrotik.make {
 
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.utils.Timer;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import org.fwiidom.osc.*;
 
	public class MakeMusicLED extends Sprite {
 
		private static const STR_LOCAL_IP:String = "169.254.73.165";
 
		private static const STR_REMOTE_IP:String = "192.168.0.200";
 
		private static const NUM_PORT:Number = 10000;
 
		private static const LOOP:String = "jens_buchert.mp3";
 
		private var oscConn:OSCConnection;
 
		private var ledArray:Array;
 
		private var _ledShapeArray:Array;
 
		private var sc:SoundChannel;
 
		private var s:Sound;
 
		public function MakeMusicLED() {
			//Initialize connection to the FLOSC server
			ledArray = [];
			oscConn = new OSCConnection(STR_LOCAL_IP, NUM_PORT);
			oscConn.addEventListener(OSCConnectionEvent.ON_CONNECT, onConnect);
			oscConn.addEventListener(OSCConnectionEvent.ON_CONNECT_ERROR, onConnectError);
			oscConn.addEventListener(OSCConnectionEvent.ON_PACKET_IN, onPacketIn);
			oscConn.addEventListener(OSCConnectionEvent.ON_PACKET_OUT, onPacketOut);
			oscConn.addEventListener(OSCConnectionEvent.ON_CLOSE, onClose);
			oscConn.connect();
		}
 
		private function onConnect(evtEvent:OSCConnectionEvent):void {
			trace("FLOSC Connection established");
			var button:Sprite = new Sprite();
			button.graphics.beginFill(0x66CC66);
			button.graphics.drawRect(20, 50, 40, 20);
			button.buttonMode = true;
			button.addEventListener(MouseEvent.CLICK, onClickHandler);
			addChild(button);
 
			s = new Sound();
			s.load(new URLRequest(LOOP));
 
			_ledShapeArray = [];
			var startX:int = 20;
 
			for(var i:int = 0; i<4; i++){
				_ledShapeArray[i] = new Shape();
				_ledShapeArray[i].graphics.beginFill(0x00FF00);
				_ledShapeArray[i].graphics.drawRect(0, 0, 8, 3);
				_ledShapeArray[i].x = startX;
				_ledShapeArray[i].y = 20;
				_ledShapeArray[i].alpha = .1;
				addChild(_ledShapeArray[i]);
				startX = startX + 10;
			}
 
		}
 
		private function onConnectError(evtEvent:OSCConnectionEvent):void {
			trace("FLOSC Connection error");
		}
 
		private function onClose(evtEvent:OSCConnectionEvent):void {
			trace("FLOSC Connection closed");
		}
 
 
		private function onPacketIn(evtOSC:OSCConnectionEvent):void {
			trace("\t>> data received: " + evtOSC.data.name + " " + evtOSC.data.data);	
		}
 
		private function onPacketOut(evtOSC:OSCConnectionEvent):void {
			trace("\t>> data sent: " + evtOSC.data.name + " " + evtOSC.data.data);	
		}
 
		private function onClickHandler(event:MouseEvent):void {
			this.addEventListener(Event.ENTER_FRAME, showAmplitude);
			sc = s.play(0, 1000);
		}
 
 
		private function showAmplitude(eventArgs:Event) {
			var v:Number = 4 * ((sc.leftPeak + sc.rightPeak)/2);
			for(var i:int = 0; i<4; i++){
				if(v > i){
					_ledShapeArray[i].alpha = 1;
					oscConn.sendOSCPacket(
						new OSCPacket("/appled/"+i.toString()+"/state", [1], STR_REMOTE_IP, NUM_PORT)
					);
				}else{
					_ledShapeArray[i].alpha = .1;
					oscConn.sendOSCPacket(
						new OSCPacket("/appled/"+i.toString()+"/state", [0], STR_REMOTE_IP, NUM_PORT)
					);
				}
			}
		}
 
 
	}
 
}

Jens Buchert
The music is the song "Mélange Eléctrique" from Jens Buchert's album Spa Lounge. Great downtempo album.


Making Things Music LED Source

The Discussion

see what everyone is saying

  • Cori February 18th, 2009 at 7:17 pm #1

    Hi I really need to use these codes in order to output the data from (HI)Max MSP to Flash. I just want to use my dance mate as a control in flash. Do I still need Flosc? Any suggestions?

  • djdonovan February 27th, 2009 at 11:22 am #2

    I haven't used Max MSP, but flosc is what is used to communicate. Since this code is old I'm not sure what changes have been made. Hopefully it's easier to get this working as I had a tedious time with it.

Respond

get in on the action.

* Required

revatio efects buy lisinopril viagra order online erectile dysfunction medications I Need To Buy Viagra drugs on line cheap msm food allergies muscle building diet osteoporosis hormon ultram dosage levitra without prescription buy viagra in canada buy desyrel buy mexiletine buy phentermine online without prescription where to buy soma lithium carbonate women and viagra medications on line ultram er alprazolam no perscription viagra online without prescription type 2 diabetes diazepam pharmacology lower high blood pressure how to get big muscles discount dog products starlix buy deltasone health vitamins ultram dosage tooth whitening dentist buy pain meds now a reliever of arthritic pain hoodia patches cheap decadron reduce cholesterol naturally asthma control cheap generic viagra online fitness muscle online treatment for aids body building online course throat infection treatment increasing breast size naturally buy celebrex online buy antibiotics cheap online clomid testosterone booster patch nutritional diet for osteoporosis treating aids in africa blood pressure diet order vitamins order viagra online cymbalta vs lexapro xanax without prescription cheap pet health care buy prevacid buy prevacid soma 250 drug for nausea where to buy soma natural cure for erectile dysfunction ear pain right side back pain dog calming pills ordering viagra dental antibiotics antifungal strategies help the pain januvia cheap diabetes type 2 bronchitis diarrhea cimetidine dose alprazolam acne tips blood pressure buy cheap tooth whitening product prevacid online water pill buspirone dosage prescription phentermine buy beconase lower leg pain vitamins for women new antibiotic drug dog health care weight loss after baby skin cancer treatments high blood pressure yerba diet self help alcoholism benicar generic cure blood clot eye infections in dogs bph prostate family pharmacy zyban pharmacy atarax generic high blood pressure drug list buy xanax online buy natural antibiotics list how to white teeth avalide generic viagra cialis levitra medician for heart attacks phentermine prescription alcoholism new treatment help for depression heart failure medicine buy retin a buy levitra online with fast delivery body fat lose weight loss web sites buy nimotop herpes simplex new blood pressure drug how do a stop smoking flu shots herpes treatment enhance sexual performance effects of celexa viagra shop increase male volume treatment for chest pain cats bladder side effects clomid face wrinkles allegra klonopin effects relieve joint pain drugs that relieve pain new cat products human parasite ultram dosing tab tramadol carb blocker medication to stop smoking order viagra online in germany anxiety info ambien viagra gel use of xanax for anxiety online drugs without prescription weight loss health health ambien online buy viagra online cheap alternative medicine cholesterol mestinon blood pressure meds treatment parkinsons disease buy viagra without prescription methocarbamol effects pet health care information what is saw palmetto buy cialis online without a prescription flu drugs celebrex information gout cures buy orlistat on line sildenafil dosage blood pressure medication names ultram dosing order viagra canadian drug online big muscle fluconazole 150mg lasix cheap ashwagandha dosage side effects of ativan body acne treatment buying viagra online without prescription body building programs cat health care natural pet products viagra order body building tips high blood calcium level estradiol pill tips for weight loss back pain medications atenolol withdrawal vermox xanax dose antibiotics bronchitis cialis cialis information how to white teeth diabetes blood sugar levels pravastatin sleep disorders remedy viagra superactive diet pills hypnotherapy cds viagra cheep carisoprodol purchase cat anxiety buy alcoholism medications nausea cure how do a stop smoking relieve joint pain oral ketoconazole clonazepam pharma california cold flu calcium channel blocker hypertension prednisone allergy Cealis Lavetra effects of levitra professional anti allergic drug drugs for hiv body building online course dog ear problem super flu quickly stop smoking bad body odor atlas rx viagra abilify 10mg nolvadex 20mg hair loss treatment uk anti obesity chloramphenicol triphala sleep disorder treatment information on ambien remedy for hair loss when are beta blockers prescribed myasthenia gravis risperdal anxiety symptoms high blood pressure cure snoring chronic heart failure medicines valium with no prescription buy alcoholism medications generic pain medication alternative treatment arthritis diovan prescription latest diet pill effects of levitra professional clomid drug xanax without prescription online hair loss for men purchase viagra online hair loss products for men lamictal viagra online usa xenical no prescription pneumonia vs bronchitis prednisone 10 mg diflucan buy celebrex online anti fungus products endep liver infection treatment order indomethacin penis enlagement augmentin medication hair loss prevention treatment for yeast infection pyridium chest pain symptoms flovent generic valium with no prescription prevention of diabetes breast enhancement new york levitra do for men ginkgo biloba prescription lipitor klonopin zoloft order medication to aid in sleeping diabetes type 2 medicines for insomnia weight loss and fitness high blood pressure info purchase levitra online cialis on line health support discount prescription medications alprazolam no perscription how to purchase cialis acne free antifungal sinus women insomnia valium maximum dosage osteoporosis bone health buspar online discount cialis levitra viagra cure bronchitis prostate cancer treatment protonix overactive bladder medications skin cancer treatment effects klonopin yeast infection remedies fluconazole interaction canada online pharmacy viagra healthy women's vitamins expected weight loss with phentermine how to purchase cialis about cialis body building buy product how to buy cialis male erectile dysfunction femara drug topamax parkinson medications male bladder problems diabetes health care system haldol medication withdrawal zyrtec buy hyzaar cat hairball remedies cheap florinef lipitor use drugs for pain celebrex cealis lavetra Viagra Cialis Levitra buy nimotop how to increase fertility buy pain medicine online insomnia sleep problems cheapest place buy viagra online tooth whitening systems haldol medication information on levitra cialis advice bactroban price of drugs seroquel for anxiety malaria preventative effects of allegra body building info vytorin generic bladder problem solutions dog health help cialis cheap no prescription beta blockers bronchitis antibiotics back pain anti-fungal natural arthritis cures buying viagra online in britain penis development cheapest generic cialis snoring woman stretch penis purchase generic viagra virility gum viagra and sports buy proscar soma on line diet supplements that work breast enhancer pills how to enlarge breast buy cialis generic online dog bowel problems pet health information enhance breast acai alpha blocker medications cialis best on-line drugstore infection dog ears enhance sexual performance weight loss male sexual power cat health info clean dogs ears ultram used for gout medicines effective weight loss program improve sexual confidence cialis levitra viagra sildenafil kamagra cat skin disorders female sexual enhancement creams prozac on line bentyl drug diarrhea in pregnancy insomnia pills helping high blood pressure buy plendil lipitor use weight loss support group online buy plan b remedies for stomach ulcers cancer cure phentermine with no perscription best weight loss products online pain doctors buy vitamin a breast enhancer how to build muscle generic abilify free pain pills by mail breast enhancement products prostate cancer support accupril cymbalta medication small penis ramipril capsules depression symptoms treatment penis enhansment blood pressure drug names herpes medications to buy free smoking treatment online carisoprodol lasix drug depression and anxiety buy griseofulvin without prescription free weight loss tips klonopin pill viagra cialis levitra diet drug online enhancement breast atacand generic get viagra prescription online verapamil drug zyban what is hoodia overactive bladder in men buy tramadol cheap treatment for chronic fungal infection zoloft buy white spots on face pediatric diarrhea paxil information buy online cialis weight loss doctor online brain cancer treatment new weight loss drug levitra pro medication for depression relieve joint pain naturally enhancement breast health information bone health general drugs for hiv nexium drug premature ejaculation cure promethazine tablets treatment for dry skin erectile dysfunction cure online viagra without prescription best weight loss solutions drug allergies buy buy cialis online now cancer drug acessrx buy tooth whitening products parkinson disease medicine free hoodia