Share My Creation Audio Sine Generator

Sine wave generator for PC, output from the sound card. I used audioTrack lib, thank you @stevel05, https://www.b4x.com/android/forum/threads/jaudiotrack.37973/#content
The code writes repeatedly an array of 36 samples of a sine wave to the sound card. The frequency is determent by the sample-rate.
B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    
    Private AT As AudioTrack
    Private rate=20 As Int
    Private Signal As Thread
    Private playButton As Button
    Private stopButton As Button
    Private genOff As Boolean
    Private amp(36), amp1(9) As Byte
    Private Slider1 As Slider
    Private set As Button
    Private Label1 As Label
    Private Slider2 As Slider
    Private freqF, freqC, smp=36 As Int
    Private Text1 As TextField
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("Layout1")
    MainForm.Show
    Signal.Initialise("Play")
    
    For i=0 To 8    '9 samples of sine wave
        amp1(i)=127*Sin(i*40*3.14/180)
    Next
    For i=0 To 35    '36 samples of sine wave
        amp(i)=127*Sin(i*10*3.14/180)
    Next
    
End Sub

Sub playButton_Action
    rate=Slider1.Value + Slider2.Value    'rate=frequency
    Text1.Text=rate
    AT.Initialize(smp*rate,8,AT.CH_CONF_MONO)
    Signal.Start(Null,"generate",Null)
    set.Enabled=True
    playButton.Enabled = False
End Sub

Private Sub Slider2_ValueChange (Value As Double)
    freqF=Slider2.Value
    Text1.Text=freqC + freqF
End Sub

Private Sub Slider1_ValueChange (Value As Double)
    freqC=Slider1.Value
    Text1.Text=freqC + freqF
End Sub


Sub set_Click
    genOff=True
    AT.Release
    Sleep(200)
    Signal.Initialise("Play")
    rate=Text1.text
    If rate>2500 Then smp=9 Else smp=36
    genOff=False
    AT.Initialize(rate*smp,8,AT.CH_CONF_MONO)
    Signal.Start(Null,"generate",Null)
End Sub


Sub generate
    Dim sdat(smp*rate) As Byte
    
    If smp=36 Then
        For i=0 To rate-1
            For j=0 To 35
                sdat(j+i*36)=amp(j)    '
            Next
        Next
    End If
    
    If smp=9 Then
        For i=0 To rate-1
            For j=0 To 8
                sdat(j+i*9)=amp1(j)    '
            Next
        Next
    End If

    AT.Start
    Do While genOff=False
        AT.Write(sdat,0,sdat.Length)
    Loop

End Sub

Sub Play_Ended(completed As Boolean,Error As String)
    
    genOff = False
    AT.Stop
End Sub

Sub MainForm_Closed
    If AT.IsInitialized Then AT.Release
End Sub

Sub stopButton_Action
    genOff = True
    set.Enabled=False
    playButton.Enabled = True
End Sub
 

Attachments

  • sine_gen405.gif
    sine_gen405.gif
    35.8 KB · Views: 1,783
  • sine_gen.gif
    sine_gen.gif
    12.8 KB · Views: 254
  • sine_gen.zip
    3.1 KB · Views: 251
Top