Imports NAudio
Imports System.IO
Imports NAudio.Utils
Public Class Form1
Private waveSource As Wave.WaveIn = Nothing
Private waveFile As Wave.WaveFileWriter = Nothing
Private waveFileWriter As Wave.WaveFileWriter
Dim ms As MemoryStream
Private Sub waveSource_DataAvailable(ByVal sender As Object, ByVal e As Wave.WaveInEventArgs)
waveFileWriter.Write(e.Buffer, 0, e.BytesRecorded)
waveFileWriter.Flush()
End Sub
Private Sub waveSource_RecordingStopped(ByVal sender As Object, ByVal e As Wave.StoppedEventArgs)
Dim fs As FileStream = File.Create(Environment.CurrentDirectory & "\test.wav")
ms.Seek(0, SeekOrigin.Begin)
ms.CopyTo(fs)
End Sub
Private Sub startBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startBTN.Click
ms = New MemoryStream()
waveFileWriter = New Wave.WaveFileWriter(New IgnoreDisposeStream(ms), waveSource.WaveFormat)
waveSource.StartRecording()
End Sub
Private Sub stopBTN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles stopBTN.Click
waveSource.StopRecording()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
waveSource = New Wave.WaveIn
AddHandler waveSource.DataAvailable, AddressOf waveSource_DataAvailable
AddHandler waveSource.RecordingStopped, AddressOf waveSource_RecordingStopped
End Sub
End Class
翻译以下帖子中的代码,这会引发" Bad Device ID"异常。
Naudio Recording and playing audio
我没有任何录音设备(或WaveIn)。这是为什么?
答案 0 :(得分:1)
是。 NAudio是开源的。您可以调试它并自己发现它。
调查WASAPI捕获。我不知道这是否有效,但这是下一步。
答案 1 :(得分:1)
C# how to record general audio from output device ( speaker ) with NAudio API
Private waveSource As Wave.WasapiLoopbackCapture = Nothing
将Wave.WaveIn
更改为Wave.WasapiLoopbackCapture
解决了我的问题。当然,我的代码仍然存在问题(请注意)。点击停止会停止捕获但不会写入文件。只有在您强制退出应用程序之后,.wav才会保存到磁盘。我可以自己解决这个问题。
答案 2 :(得分:0)
在Private Sub waveSource_RecordingStopped
中添加此内容以查看.wav
,而无需关闭应用程序:
fs.Dispose()