本文實例講述了Python調用系統底層API播放wav文件的方法。分享給大家供大家參考,具體如下:
這里未使用其他庫,只是使用 pywin32 調用系統底層 API 播放 wav 文件。
具體代碼如下:
# Our raison d'etre - playing soundsimport pywintypesimport structimport win32eventimport win32com.directsound.directsound as dsimport osWAV_HEADER_SIZE = struct.calcsize('<4sl4s4slhhllhh4sl')def wav_header_unpack(data): '''解包wav文件頭信息''' (riff, riffsize, wave, fmt, fmtsize, format, nchannels, samplespersecond, / datarate, blockalign, bitspersample, data, datalength) = struct.unpack('<4sl4s4slhhllhh4sl', data) if riff != b'RIFF' or fmtsize != 16 or fmt != b'fmt ' or data != b'data': raise ValueError wfx = pywintypes.WAVEFORMATEX() wfx.wFormatTag = format wfx.nChannels = nchannels wfx.nSamplesPerSec = samplespersecond wfx.nAvgBytesPerSec = datarate wfx.nBlockAlign = blockalign wfx.wBitsPerSample = bitspersample return wfx, datalength# 播放wav文件,直到結束sound_file = "音效-足球觀眾的歡呼聲.wav"fname = os.path.join(os.path.dirname(__file__), sound_file)f = open(fname, 'rb')# 讀取/解包wav文件頭hdr = f.read(WAV_HEADER_SIZE)wfx, size = wav_header_unpack(hdr)d = ds.DirectSoundCreate(None, None)d.SetCooperativeLevel(None, ds.DSSCL_PRIORITY)sdesc = ds.DSBUFFERDESC()sdesc.dwFlags = ds.DSBCAPS_STICKYFOCUS | ds.DSBCAPS_CTRLPOSITIONNOTIFYsdesc.dwBufferBytes = sizesdesc.lpwfxFormat = wfxbuffer = d.CreateSoundBuffer(sdesc, None)event = win32event.CreateEvent(None, 0, 0, None)notify = buffer.QueryInterface(ds.IID_IDirectSoundNotify)notify.SetNotificationPositions((ds.DSBPN_OFFSETSTOP, event))buffer.Update(0, f.read(size))buffer.Play(0)win32event.WaitForSingleObject(event, -1)更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答