Naudio vb.net I record sound from the speakers

Pagina: 1
Acties:

Vraag


  • Richard1234
  • Registratie: September 2026
  • Laatst online: 06:34
I record sound from the speakers, but I hear my self with recording.
Know someOne why ?
Thanks in Advance.
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
Imports System
Imports System.Globalization
Imports System.IO
Imports Windows.System.Management
Imports System.Media
Imports System.Reflection.Emit
Imports System.Speech.AudioFormat
Imports System.Speech.Synthesis
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Threading
Imports System.Threading.Thread
Imports NAudio
Imports NAudio.CoreAudioApi
Imports NAudio.Wave
Imports Windows.Media.SpeechSynthesis
Public Class Form1

    Private writer As WaveFileWriter
    Dim klik As Byte = 0
    Dim StopWatch As New Diagnostics.Stopwatch
    Public recorder
    Dim wave
    Dim wavefilewriter


    Dim synth = New Speech.Synthesis.SpeechSynthesizer()
    Private waveWriter As WaveFileWriter
    ' define the TimeSpan format and culture
    Private Const CustomTimeSpanFormat As String = "hh\:mm\:ss\,fff"
    Private ReadOnly _culture As CultureInfo = CultureInfo.CurrentCulture

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        synth.Rate = 2
        synth.SelectVoiceByHints(Speech.Synthesis.VoiceGender.Male, VoiceAge.Adult, 2, CultureInfo.GetCultureInfo("nl-NL"))

        ' Create the enumerator to discover audio endpoints
        Dim enumerator As New MMDeviceEnumerator()

        ' Enumerate only the active audio rendering (playback) devices
        Dim devices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)


        For Each device As MMDevice In devices
            ' FriendlyName gives you the name shown in Windows settings (e.g., "Speakers (Realtek Audio)")
            TextBox2.Text = TextBox2.Text & ($"Name: {device.FriendlyName}") & vbCrLf
            TextBox2.Text = TextBox2.Text & ($"ID: {device.ID}") & vbCrLf
            TextBox2.Text = TextBox2.Text & (New String("-"c, 30)) & vbCrLf
        Next

    End Sub


    Private Async Sub ButtonStartDelay_Click(sender As Object, e As EventArgs) Handles ButtonStartDelay.Click
        klik = 0
        Me.StopWatch.Restart()
        TimerDelay.Start()
        Me.StopWatch.Start()
        TextBoxInput.Enabled = True
        ButtonStartDelay.Enabled = False
        ButtonStartDelay.Text = "Busy..."
        TextBoxOutput.Clear()


        Dim enumerator As New MMDeviceEnumerator()
        Dim captureDevices = enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active)

        Dim selectedDevice As MMDevice = Nothing

        ' 2. Find the device that contains or matches your target FriendlyName
        For Each device As MMDevice In captureDevices
            If device.FriendlyName.IndexOf("Luidsprekers (Realtek(R) Audio)", StringComparison.OrdinalIgnoreCase) >= 0 Then
                selectedDevice = device
            End If
            Exit For
        Next

        Dim path = "e:\Ondertitel.wav"
        Dim recorder = New WasapiRecorderBuilder() _
            .WithDevice(selectedDevice) _
            .Build()

        writer = New WaveFileWriter(path, recorder.WaveFormat)
        AddHandler recorder.DataAvailable,
          Sub(buffer, flags, devicePosition, qpcPosition)
              writer.Write(buffer)
          End Sub
        recorder.StartRecording()

        Dim previousWaitTime As TimeSpan = TimeSpan.Zero

              ProgressBar1.Maximum = 1
              ProgressBar1.Value = 0


              Dim o As Integer = 1
              For Each line As String In TextBoxInput.Lines
                  If klik = 1 Then Exit For

                  ' try to parse the TimeSpan using the custom format and culture
                  Dim currentWaitTime As TimeSpan
                  If (Not TimeSpan.TryParseExact(line, CustomTimeSpanFormat, _culture, currentWaitTime)) Then

                      AppendLine(TextBoxOutput, $"Invalid TimeSpan format: {line}")

                      TextBoxInput.Text = line


                      If line.Length >= 1 AndAlso line.Length <= 3 Then
                          TextBoxInput.Text = Regex.Replace(TextBoxInput.Lines(0), "[1-999]", "")
                      Else
                          synth.resume
                          synth.SpeakAsync(TextBoxInput.Text)

                      End If
                      Continue For
                  End If

                  ' calculate the delay
                  Dim delay As TimeSpan = currentWaitTime - previousWaitTime
                  AppendLine(TextBoxOutput, $"Wait {delay.TotalSeconds:F3} seconds")

                  With Me.TextBoxOutput
                      .SelectionStart = Len(.Text)
                      .ScrollToCaret()
                  End With

                  With Me.TextBoxInput
                      .SelectionStart = Len(.Text)
                      .ScrollToCaret()
                  End With

                  If (delay > TimeSpan.Zero) Then
                      ' only delay if there's actually time to wait
                      ProgressBar1.Maximum = delay.TotalSeconds()
                      TimerDelay.Start()
                      Await Task.Delay(delay)

            End If

                  previousWaitTime = currentWaitTime
              Next
        recorder.StopRecording()
        TextBoxInput.Enabled = True
              ButtonStartDelay.Enabled = True
              ButtonStartDelay.Text = "Subtitle to voice"
          End Sub

    Private Sub TimerDelay_Tick(sender As Object, e As EventArgs) Handles TimerDelay.Tick
        Dim elapsed As TimeSpan = Me.StopWatch.Elapsed
        Label2.Text = String.Format("{0:00}:{1:00}:{2:00}:{3:000}", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds, elapsed.Milliseconds)

        If (ProgressBar1.Value = ProgressBar1.Maximum) Then
            TimerDelay.Stop()
        Else
            ProgressBar1.Value += 1
        End If
    End Sub

    Private Shared Sub AppendLine(destination As TextBox, line As String)
        destination.Lines = destination.Lines.Concat({line}).ToArray()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        OpenFileDialog1.Title = "Please select a subtitle file"
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.Filter = "Subtitle Files|*.srt"

        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Dim content As String = File.ReadAllText(OpenFileDialog1.FileName, Encoding.UTF8)
            TextBoxInput.Text = content
        End If
        TextBoxInput.Lines = TextBoxInput.Lines.Where(Function(line) line <> String.Empty).ToArray()

        Dim Term As String = " -->"
        Dim lines() As String = TextBoxInput.Lines
        For x As Integer = 0 To lines.GetUpperBound(0)
            If lines(x).Contains(Term) Then
                lines(x) = lines(x).Substring(0, lines(x).IndexOf(Term))
            End If
        Next
        TextBoxInput.Lines = lines
    End Sub



    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        klik = 1
        TextBoxInput.Enabled = True
        ButtonStartDelay.Enabled = True
        ButtonStartDelay.Text = "Subtitle to voice"
        synth.SpeakAsyncCancelAll()
        synth.Pause()
        klik = 1
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim deviceCount As Integer = WaveIn.DeviceCount

        For i As Integer = 0 To deviceCount - 1
            Dim capabilities As WaveInCapabilities = WaveIn.GetCapabilities(i)
            TextBox2.Text = ($"Device ID: {i} - Name: {capabilities.ProductName}")
        Next
    End Sub
End Class