diff --git a/GeneratingDynamicSound/Assets/openfl.svg b/GeneratingDynamicSound/Assets/openfl.svg new file mode 100644 index 0000000..6d02f40 --- /dev/null +++ b/GeneratingDynamicSound/Assets/openfl.svg @@ -0,0 +1,593 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GeneratingDynamicSound/Source/Main.hx b/GeneratingDynamicSound/Source/Main.hx new file mode 100644 index 0000000..5452aa3 --- /dev/null +++ b/GeneratingDynamicSound/Source/Main.hx @@ -0,0 +1,49 @@ +package; + +import openfl.display.Sprite; +import openfl.events.SampleDataEvent; +import openfl.media.Sound; + +class Main extends Sprite +{ + public var squareFreq = 220.0; + public var sinFreq = 880.0; + public var gain = 0.30; + public var rate = 44100; + + public function new():Void { + super(); + + var s = new Sound(); + s.addEventListener(SampleDataEvent.SAMPLE_DATA, generateWave); + s.play(); + } + + // Generator function: + // * 2 values must be written per sample (left and right). + // * This function generates a square wave on the left channel, + // and a sine wave on the right channel. + // * Between 2048 (at a minimum) and 8192 samples must be + // generated by the event handler. + // * If samples are generated, then it's less likely that loud + // pops will be heard due to running out of audio to play. + // * If fewer samples are generated, then the event handler will + // be called more often, which could be desirable if tight + // control over the audio is desired. + + private function generateWave(event:SampleDataEvent):Void { + var squarePitch = rate / squareFreq; + var sinPitch = rate / sinFreq; + + for (i in 0...8192) { + var squarePhase = ((event.position + i) % squarePitch) / squarePitch; + var sinPhase = ((event.position + i) % sinPitch) / sinPitch; + + var squareSample = (squarePhase < 0.5) ? gain : -gain; + var sinSample = Math.sin(2 * Math.PI * sinPhase) * gain; + + event.data.writeFloat(squareSample); + event.data.writeFloat(sinSample); + } + } +} diff --git a/GeneratingDynamicSound/project.xml b/GeneratingDynamicSound/project.xml new file mode 100644 index 0000000..022eb48 --- /dev/null +++ b/GeneratingDynamicSound/project.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/haxelib.json b/haxelib.json index 63e45e6..1fce850 100644 --- a/haxelib.json +++ b/haxelib.json @@ -6,6 +6,6 @@ "description": "OpenFL samples", "version": "1.3.0", "releasenote": "Improvements for OpenFL 1.3 release", - "contributors": [ "singmajesty" ], + "contributors": [ "singmajesty", "type1j" ], "dependencies": {} }