本文實(shí)例講述了Python調(diào)用系統(tǒng)底層API播放wav文件的方法。分享給大家供大家參考,具體如下:
這里未使用其他庫(kù),只是使用 pywin32 調(diào)用系統(tǒng)底層 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文件,直到結(jié)束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)更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門(mén)與進(jìn)階經(jīng)典教程》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選