Code archives/Audio/(BMX) Synthesize a simple sound sample

This code has been declared by its author to be Public Domain code.

Download source code

(BMX) Synthesize a simple sound sample by Perturbatio2007
It's very basic but it works, includes a primitive waveform drawing function
SuperStrict
Graphics 1024,768,0,0

Global Quit:Int = False
Const SampleSize:Int = 100000
Global sample:TAudioSample = TAudioSample.Create(SampleSize, 44100, SF_STEREO16BE)
Global sampleData:Byte[SampleSize] 

Print sample.length
Print getSampleLength(sample)

Function getSampleLength:Float(sample:TAudioSample)
	Return Float( (sample.length / Float( (sample.hertz * 60) ) ) * 60)
End Function



Function drawWave(sample:TAudioSample)
	Local x:Int, y:Int
	Local xscale:Double = sample.length/GraphicsWidth()
	For x = 0 Until sample.length Step 100
		y = sample.samples[x]
		If (y > 0) Then
			SetColor(255,y,y)
			DrawLine((x/xscale)-1, sample.samples[x-1], x/xscale, y)
			'DrawLine((x/xscale)-1, Abs(sample.samples[x-1]-255)+255, x/xscale, Abs(y-255)+255)
		End If
	Next
End Function

SeedRnd MilliSecs()

For Local m:Int = 0 Until SampleSize
	sample.samples[m] = Sin(m)*128
	If (m Mod 1000) > 900 Then sample.samples[m] = 100
Next

Local sound:TSound = LoadSound(sample)
Local channel:TChannel = PlaySound(sound)

While Not Quit
	Cls
	drawWave(sample)
	If channel.playing() Then
		SetColor(255,0,0)
		DrawText("Playing", 10, 300)
	Else
		SetColor(255,255,255)
		DrawText("Not Playing (Press space)", 10, 300)
	EndIf
	
	Flip
	If KeyDown(KEY_SPACE) And Not channel.playing() Then channel = PlaySound(sound)
	If KeyDown(KEY_ESCAPE) Then quit = True
Wend
End

Comments

ImaginaryHuman2007
Is there a way to get this to play a looping sound which you can modify, so that you have one long endless sound that is being generated as it is played, like using a long sound buffer and modifying the part that isn't playing (like a double buffer)?


Perturbatio2007
I was wondering if there was a way to access the data that the TSound object uses (I presume it makes a copy of the data when you use loadsound on the TAudioSample. A bit of investigation may be in order (but not right now since I'm not at home).


Code Archives Forum