As3 Sine Wave Effects/Song generator


(Frazer Bennett Wilford) #1

Simply call

 add(new Note([frequency1, frequency2, frequency3...], speedrate, volume));

To play interesting sounding 8bit sounds. I use this for sound effects and even custom songs ingame. I made this for a game I made for a JAM. But feel free to use it. It is not perfect, but it works for what it is. Also, if anyone has any idea on how to improve it, for instance making frequency based on time, rather than per sound, that’d be awesome!

Speedrate (Samples) must be between 2048 and 8192

import net.flashpunk.Entity;
import net.flashpunk.FP;
import flash.events.SampleDataEvent;
import flash.media.Sound;

/**
 * ...
 * @author Frazer Bennett Wilford
 */
public class Note extends Entity
{
	public var note:Sound = new Sound();  
	public var note_to_play:Array = [];
	public var amplitude:Number = 1;
	
	public function Note(freq:Array, sample_set:int, amplitudeSET:Number) 
	{
		amplitude = amplitudeSET;
		samples = sample_set;
		note_to_play = freq;
		note.addEventListener(SampleDataEvent.SAMPLE_DATA, NoteGenerator); 
	    note.play();
	}
	
	public var frequency:Number = 0; // frequency of note
	public var note_pos:int = 0; // which note in the song to play next
	public var samples:int = 8192; // amount of samples per note
	
	public function NoteGenerator(event:SampleDataEvent):void 
	{ 
		if (note_pos == note_to_play.length)
		{
			note.removeEventListener(SampleDataEvent.SAMPLE_DATA, NoteGenerator);
			FP.world.remove(this);
		}
		
		///// NOTE 
		frequency = note_to_play[note_pos]
		note_pos += 1;
	
		for (var i:int = 0; i < samples; i++) 
		{ 
			var n:Number = Math.sin((((2 * Math.PI) / samples) * (i * (frequency))) / 2);
			///// make a square wave //////
			if (n > 0)
			{
				n = 1 * amplitude;
			}else {
				n = -1 * amplitude;
			}
			/////////////////////////////
			event.data.writeFloat(n); 
			event.data.writeFloat(n); 
		} 
	}
	
	
}