vb.netaudiobeep

Generate sound frequency in windows - VB.Net


i need to generate a square wave sound in windows . I'm using this code :

System.console.beep(500,500)

But it don't works very well : It takes a bit to play the sound . I have a 2.7 GHZ CPU , so i don't think my computer is slow .

Does someone know a library or another code to play frequencies in windows ?


Solution

  • Imports:

    Imports System.IO
    Imports System.Media
    

    Call:

    FrequencyBeep(500, 500, 10000)
    

    Sub:

    Public Shared Sub FrequencyBeep(ByVal Amplitude As Integer, ByVal Frequency As Integer, ByVal Duration As Integer)
        Dim A As Double = ((Amplitude * (System.Math.Pow(2, 15))) / 1000) - 1
        Dim DeltaFT As Double = 2 * Math.PI * Frequency / 44100.0
        Dim Samples As Integer = 441 * Duration / 10
        Dim Bytes As Integer = Samples * 4
    
        Dim Hdr As Integer() = {1179011410, 36 + Bytes, 1163280727, 544501094, 16, 131073, 44100, 176400, 1048580, 1635017060, Bytes}
    
        Using MS As MemoryStream = New MemoryStream(44 + Bytes)
    
            Using BW As BinaryWriter = New BinaryWriter(MS)
    
                For I As Integer = 0 To Hdr.Length - 1
                    BW.Write(Hdr(I))
                Next
    
                For T As Integer = 0 To Samples - 1
                    Dim Sample As Short = System.Convert.ToInt16(A * Math.Sin(DeltaFT * T))
                    BW.Write(Sample)
                    BW.Write(Sample)
                Next
    
                BW.Flush()
                MS.Seek(0, SeekOrigin.Begin)
    
                Using SP As SoundPlayer = New SoundPlayer(MS)
                    SP.PlaySync()
                End Using
            End Using
        End Using
    End Sub