Skip to content

Instantly share code, notes, and snippets.

@Benshi
Last active July 15, 2021 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Benshi/21c47c2c2873b236ca69889449e6c758 to your computer and use it in GitHub Desktop.
Save Benshi/21c47c2c2873b236ca69889449e6c758 to your computer and use it in GitHub Desktop.
[VB] NAudio による録音サンプル
Partial Public Class RecordingForm
Inherits System.Windows.Forms.Form
Private recordingData As System.IO.MemoryStream '録音データ
' NuGet で NAudio パッケージを組み込んでおくこと
Private WithEvents waveIn As NAudio.Wave.WaveInEvent
Private writer As System.IO.Stream
Private Sub waveIn_DataAvailable(sender As Object, e As NAudio.Wave.WaveInEventArgs) Handles waveIn.DataAvailable
writer?.Write(e.Buffer, 0, e.BytesRecorded)
writer?.Flush()
End Sub
Private Sub waveIn_RecordingStopped(sender As Object, e As NAudio.Wave.StoppedEventArgs) Handles waveIn.RecordingStopped
writer?.Flush()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' ComboBox1 で入力音源を選択させる
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
ComboBox1.DisplayMember = "ProductName"
Button1.Text = "録音開始"
Button2.Text = "録音停止"
Button2.Enabled = False
Button3.Text = "入力ソースの再取得"
Button3.PerformClick()
End Sub
''' <summary>録音開始</summary>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
If ComboBox1.SelectedIndex < 0 OrElse waveIn IsNot Nothing Then
' 入力音源が無い場合や、既に録音処理中であれば何もしない
Return
End If
waveIn = New NAudio.Wave.WaveInEvent() With {.DeviceNumber = ComboBox1.SelectedIndex}
waveIn.WaveFormat = New NAudio.Wave.WaveFormat(44100, DirectCast(ComboBox1.SelectedItem, NAudio.Wave.WaveInCapabilities).Channels)
recordingData = New System.IO.MemoryStream()
writer = New NAudio.Wave.WaveFileWriter(recordingData, waveIn.WaveFormat)
waveIn.StartRecording()
Button3.Enabled = False
Button2.Enabled = True
End Sub
''' <summary>録音停止</summary>
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Button2.Enabled = False
waveIn.StopRecording()
waveIn.Dispose()
waveIn = Nothing
writer.Close()
writer = Nothing
' 取得したバイナリをファイルに保存するかどうかはお好みで
System.IO.File.WriteAllBytes("C:\AudioData\example.wav", recordingData.ToArray())
Button1.Enabled = True
Button3.Enabled = True
End Sub
''' <summary>入力ソースの再取得</summary>
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ComboBox1.BeginUpdate()
ComboBox1.Items.Clear()
If NAudio.Wave.WaveInEvent.DeviceCount > 0 Then
Button1.Enabled = True
For deviceNumber As Integer = 0 To NAudio.Wave.WaveInEvent.DeviceCount - 1
ComboBox1.Items.Add(NAudio.Wave.WaveInEvent.GetCapabilities(deviceNumber))
Next
ComboBox1.SelectedIndex = 0
Else
Button1.Enabled = False
End If
ComboBox1.EndUpdate()
End Sub
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment