def testRecord(self): d = ds.DirectSoundCaptureCreate(None, None) sdesc = ds.DSCBUFFERDESC() sdesc.dwBufferBytes = 352800 # 2 seconds sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX() sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM sdesc.lpwfxFormat.nChannels = 2 sdesc.lpwfxFormat.nSamplesPerSec = 44100 sdesc.lpwfxFormat.nAvgBytesPerSec = 176400 sdesc.lpwfxFormat.nBlockAlign = 4 sdesc.lpwfxFormat.wBitsPerSample = 16 buffer = d.CreateCaptureBuffer(sdesc) event = win32event.CreateEvent(None, 0, 0, None) notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify) notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event)) buffer.Start(0) win32event.WaitForSingleObject(event, -1) event.Close() data = buffer.Update(0, 352800) fname = os.path.join(win32api.GetTempPath(), 'test_directsound_record.wav') f = open(fname, 'wb') f.write(wav_header_pack(sdesc.lpwfxFormat, 352800)) f.write(data) f.close()
def __init__(self, nchnl=1, sps=16000, bps=16, t=0.1): dsc = directsound.DirectSoundCaptureCreate(None, None) #创建设备对象 cdesc = directsound.DSCBUFFERDESC() #创建DSCBUFFERDESC结构对象 self.bSize = int(sps * nchnl * bps / 8 * t) cdesc.dwBufferBytes = self.bSize #缓存大小 cdesc.lpwfxFormat = pywintypes.WAVEFORMATEX() #DirectSound数据块格式 cdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM cdesc.lpwfxFormat.nChannels = nchnl cdesc.lpwfxFormat.nSamplesPerSec = sps cdesc.lpwfxFormat.nAvgBytesPerSec = int(sps * nchnl * bps / 8) cdesc.lpwfxFormat.nBlockAlign = int(nchnl * bps / 8) cdesc.lpwfxFormat.wBitsPerSample = bps self.buffer = dsc.CreateCaptureBuffer(cdesc) #创建缓冲区对象 self.evt = [] for i in range(2): self.evt.append(win32event.CreateEvent(None, 0, 0, None)) #创建两个事件通知 Notify = self.buffer.QueryInterface( directsound.IID_IDirectSoundNotify) #创建事件通知接口 Notify.SetNotificationPositions([ (int(self.bSize / 2) - 1, self.evt[0]), (self.bSize - 1, self.evt[1]) ]) #error #设置两个通知位置,缓冲区每填充bSize/2个样本即发送一个通知消息 self.data = b'' #用于实时存储捕获的音频数据 self.STATUS = False #录音状态标志 self.wfx = cdesc.lpwfxFormat #存储声音格式
def testCreate(self): """DirectSoundCreate()""" try: d = ds.DirectSoundCaptureCreate(None, None) except pythoncom.com_error as exc: if exc.hresult != ds.DSERR_NODRIVER: raise raise TestSkipped(exc)
import struct import win32event import win32com.directsound.directsound as ds def wav_header_pack(wfx, datasize): return struct.pack('<4sl4s4slhhllhh4sl', 'RIFF', 36 + datasize, 'WAVE', 'fmt ', 16, wfx.wFormatTag, wfx.nChannels, wfx.nSamplesPerSec, wfx.nAvgBytesPerSec, wfx.nBlockAlign, wfx.wBitsPerSample, 'data', datasize) d = ds.DirectSoundCaptureCreate(None, None) sdesc = ds.DSCBUFFERDESC() sdesc.dwBufferBytes = 352800 # 2 seconds sdesc.lpwfxFormat = pywintypes.WAVEFORMATEX() sdesc.lpwfxFormat.wFormatTag = pywintypes.WAVE_FORMAT_PCM sdesc.lpwfxFormat.nChannels = 2 sdesc.lpwfxFormat.nSamplesPerSec = 44100 sdesc.lpwfxFormat.nAvgBytesPerSec = 176400
def testCreate(self): '''DirectSoundCreate()''' d = ds.DirectSoundCaptureCreate(None, None)