Naudio 录音
Imports NAudio.Wave
Dim wav As New WaveIn
wav.BufferMilliseconds = 200 '缓冲区大小= ; 200 = 6400;100 = 3200
wav.NumberOfBuffers = 12 '缓冲区数量
wav.WaveFormat = New WaveFormat(16000, 16, 1) '格式 16000
AddHandler wav.DataAvailable, AddressOf waveIn_DataAvailable
wav.StartRecording() '录音启动
‘wav.StopRecording()
Private Sub waveIn_DataAvailable(sender As Object, e As WaveInEventArgs)
Buffer.BlockCopy(e.Buffer, 0, WavData16, b, e.BytesRecorded) '偏移量为字节
end sub
包装类:
Imports NAudio.Wave
Public Class WaveRecord
Dim IsClose As Boolean = False
Dim wav As New WaveIn
Dim _dataArrivefun As DataArrive
Public Sub Start(dataArriveFun As DataArrive)
IsClose = False
_dataArrivefun = dataArriveFun
wav.BufferMilliseconds = 200 '200 = 6400;100 = 3200
wav.NumberOfBuffers = 6 '缓冲区大小
wav.WaveFormat = New WaveFormat(16000, 16, 1) '格式 16000
AddHandler wav.DataAvailable, AddressOf waveIn_DataAvailable
wav.StartRecording() '录音启动
End Sub
''' <summary>
''' 回调函数
''' </summary>
''' <param name="lpdata"></param>
''' <param name="datalen"></param>
''' <returns></returns>
Public Delegate Function DataArrive(lpdata As Byte(), datalen As Integer)
Private Sub waveIn_DataAvailable(sender As Object, e As WaveInEventArgs)
If IsClose Then
Return
End If
_dataArrivefun(e.Buffer, e.BytesRecorded)
End Sub
Public Sub Close()
IsClose = True
wav.StopRecording()
End Sub
End Class
WAVAPI 录音实现(不建议使用),可参考Naudio源码
Imports System.Runtime.InteropServices
Imports System.IO
Imports System.Threading
'使用步骤:
'1.声明
' Dim waverecord As New WaveRecordApi
'2.定义录音数据到达回调函数
' Public Function DataArrive(lpdata As Byte(), datalen As Integer)
' If WaveDataLength >= 6400 * 10 Then
' Exit Function
' End If
' lpdata.CopyTo(WaveDataBuffer, WaveDataLength)
' WaveDataLength = WaveDataLength + datalen
'End Function
'3.开始录音
' waverecord.Start(AddressOf DataArrive)
'4.结束录音
' waverecord.Close()
'1.读线地址错误(被回收了 0x000000005 读写地址错误 gchandle.alloc pinned
'2.线程错误waitfor (使用了本机调试
'3.发声与录音干扰 speech cancelall导致,debug下
'4.获取的数据中,有非DATA数据 即非定义的whdr,故WAVEINADDBUFFER错误
'注意 1.全局变量的定义 :产生的问题 程序退出,或是无数据
'注意2.非托管函数与托管函数之间的转换 INTPTR 为非托管
'注意4.C的定义 与VB的定义 DECLARE 不同 VB6的LONG为32位 改为INTEGER ;delegate 即是回调地址 :产生问题pinvok 错误;正确的声明 www.pinvoke.net处有,但有些需改
'注意5.线程与安全线程不同,否则GETMESSAGE不能使用
'注意6.uintptr与intptr不同,需要修改
'注意7.waveInAddBuff 处的wavehdr结构 非intptr,产生问题:录音刚开始处缺失
'包含功能:WAVE API录音与播放
'''录音程序
''' 函数
''' Start() 开始录音
''' Close() 结束录音
'''播放声音
''' 函数
''' WaveOut
#Const _Debug = 0 '调试信息
#Const _WriteFile = 0 '写入文件否
Public Class WaveRecordApi
#Region "wave定义结构与声明"
Private Const MM_WIM_OPEN As Integer = &H3BE
Private Const MM_WIM_CLOSE As Integer = &H3BF
Private Const MM_WIM_DATA As Integer = &H3C0
Private Const WAVE_MAPPER As Integer = -1
Private Const WAVE_FORMAT_PCM As I