Play 2 different frequencies one Left and one Right

35 views Asked by At

I am using Basic4Android (B4A).

I created a sub that plays 2 different frequencies,

Let's call them FreqLeft and FreqRight.

Both of them is playing in one channel (Mono).

I want to play FreqLeft in the Left Channel (Left Ear Audio Speaker) and FreqRight in the Right Channel (Right Ear Audio Speaker)

And this is the code:

Public Sub GenBB (DurationMs As Double, FreqLeft As Double, FreqRight As Double)
    Dim Samples As Int = 8000 * DurationMs / 1000
    Dim Tone(2 * Samples) As Byte
    
    For i = 0 To Samples - 1
        Dim sample1 As Double = Sin(2 * cPI * i / (8000 / FreqLeft)) * 16383.5
        Dim sample2 As Double = Sin(2 * cPI * i / (8000 / FreqRight)) * 16383.5
        
        
        Tone(2 * i + 0) = Bit.And(sample1 + sample2, 0x00ff)
        Tone(2 * i + 1) = Bit.UnsignedShiftRight(Bit.And(sample1 + sample2, 0xff00), 8)
    Next
    
    streamer1.Write(Tone)
End Sub

To make it easy to understand, this one only plays one frequency. How can I play it on the left audio speaker channel or the right audio speaker channel?

Public Sub GenerateTone (DurationMs As Double, Frequency As Double)
    Dim Samples As Int = 8000 * DurationMs / 1000
    Dim Tone(2 * Samples) As Byte
    
    For i = 0 To Samples - 1
        Dim Sample As Double = Sin(2 * cPI * i / (8000 / Frequency)) * 16383.5
        
        Tone(2 * i + 0) = Bit.And(Sample, 0x00ff)
        Tone(2 * i + 1) = Bit.UnsignedShiftRight(Bit.And(Sample, 0xff00), 8)
    Next
    
    streamer1.Write(Tone)
End Sub

Thank you in advance.

1

There are 1 answers

0
Hedi On

Solved! Do all these steps and it will work.

First of all, add this to Starter 'Sub Process_Globals':

Public Streamer1 As AudioStreamer

In Starter 'Sub Service_Create' add this:

Try
    Streamer1.Initialize("streamer1", 4000, False, 16, Streamer1.VOLUME_MUSIC)
    Streamer1.StartPlaying
Catch
    Log(LastException)
End Try

And this is the code, add this sub to Starter:

Public Sub GenBB (DurationMs As Double, FreqLeft As Double, FreqRight As Double)
Dim Samples As Int = 4000 * 2 * DurationMs / 1000
Dim Tone(2 * Samples) As Byte

For i = 0 To Samples - 1 Step 2
    
    Dim Sample1 As Double = Sin(1 * cPI * i / (4000 / FreqLeft))
    Dim Left As Short = Sample1 * 32767
    
    Dim Sample2 As Double = Sin(1 * cPI * i / (4000 / FreqRight))
    Dim Right As Short = Sample2 * 32767
    
    Tone(2 * i + 1) = Bit.UnsignedShiftRight(Bit.And(Left, 0xff00), 8)
    Tone(2 * i + 3) = Bit.UnsignedShiftRight(Bit.And(Right, 0xff00), 8)
Next

    Streamer1.Write(Tone)
End Sub

For playing in Main:

Starter.Streamer1.StartPlaying
Starter.GenBB(5000, 432, 436) 'Milliseconds, Left channel, Right channel:

For playing in Starter:

Streamer1.StartPlaying
GenBB(5000, 432, 436) 'Milliseconds, Left channel, Right channel:

For stop playing in Main:

Starter.Streamer1.StopPlaying

For stop playing in Starter:

Streamer1.StopPlaying