- Joined
- Jan 2, 2020
- Messages
- 1,282
Here's an example how you can use what I showed in an earlier file-tutorial.
This time we create sounds on the fly. This means we can create sound-effects and music dynamically.
We can synthesize media and we can hide media.
This is tested on macOS.
This time we create sounds on the fly. This means we can create sound-effects and music dynamically.
We can synthesize media and we can hide media.
This is tested on macOS.
Cerberus:
' Create a soundfile that's supported across all platforms
Strict
Import mojo2
Import brl
Import OS
Function Main : Int()
New Game()
Return 0
End
Class Game Extends App
Field canvas : Canvas
Field bits:Int = 16, samplerate : Int = 44100
Field samples : Int, waveform : Int[]
' Synthesizer parameters
Field seconds : Float = 2
Field hz : Float = 440.0
Field amplitude : Int = 32000
Field flag:Int = 0
Field noise:Sound
Method OnCreate : Int()
canvas = New Canvas
samples = samplerate * seconds ; waveform = New Int[samples]
' Generate sound (Generates a simple sinewave of said hz and amplitude, with a duration of said seconds)
For Local i:Int = 0 Until samples
Local t:Float = Float(i) / Float(samplerate) ; waveform[i] = amplitude * Sin(hz * t * 360.0)
Next
Return 0
End
Method OnRender : Int()
canvas.Clear
' Save sound
If flag = 0
SaveWav( "cerberus://data/mysound.wav")
flag = 1 ; Print "File saved"
Endif
' Load sound
If flag = 1
noise = LoadSound("mysound.wav")
flag = 2 ; Print "File loaded"
Endif
' Play sound
If flag = 2 And MouseDown(0) Then PlaySound noise,0 ; Print "File played"
canvas.Flush
Return 0
End
Method SaveWav:Void(path:String) ' SAVE 16-BIT .WAV FILE
Local bits:Int = 16
Local channels:Int = 1
Local samples:Int = waveform.Length
Local bytes:Int = bits / 8
Local sum : Int = samples * bytes
Local dump := New FileStream(path,"w")
dump.WriteString "RIFF" ' A simple CD Quality Header (16-bit, 44.1 Khz)
dump.WriteInt sum + 36
dump.WriteString "WAVE"
dump.WriteString "fmt "
dump.WriteInt 16
dump.WriteShort 1 ' 16-bit
dump.WriteShort channels
dump.WriteInt samplerate
dump.WriteInt samplerate * channels * bytes
dump.WriteShort channels * bytes
dump.WriteShort bits
dump.WriteString "data"
dump.WriteInt sum
For Local temp:Int = 0 To samples-1 ' Waveform is stored here
dump.WriteShort(waveform[temp])
Next
If sum Mod 2 Then dump.WriteByte 0 ' Wav files wants to be even in length
dump.Close
End
End
Last edited: