简体   繁体   English

从.wav文件中提取一段

[英]Extract a segment from a .wav file

I have the following code to load a .wav file and play it: 我有以下代码来加载.wav文件并播放它:

import base64
import winsound
with open('file.wav','rb') as f:
    data = base64.b64encode(f.read())


winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)

It plays the file no problem but now I would like to extract a 'chunk' let's say from 233 to 300 and play that portion only. 它播放文件没有问题,但是现在我想提取一个“块”,比如说从233到300,然后仅播放该部分。

seg = data[233:300]
winsound.PlaySound(base64.b64decode(seg), winsound.SND_MEMORY)

I Get: TypeError: 'sound' must be str or None, not 'bytes' 我得到: TypeError: 'sound' must be str or None, not 'bytes'

PlaySound() is expecting a fully-formed WAV file, not a segment of PCM audio data. PlaySound()需要一个完整的WAV文件,而不是一段PCM音频数据。 From the docs for PlaySound() , the underlying function called by Python's winsound : PlaySound()的文档中,Python的winsound调用的基础函数:

The SND_MEMORY flag indicates that the lpszSoundName parameter is a pointer to an in-memory image of the WAVE file . SND_MEMORY标志指示lpszSoundName参数是指向WAVE文件的内存图像指针。

(emphasis added) (强调)

Rather than playing around with the internals of WAV files (though that isn't too hard , if you're interested), I'd suggest a more flexible audio library like pygame's. 我建议不要使用WAV文件的内部结构(尽管如果您感兴趣的话, 也不太难 ),我建议您使用一种更灵活的音频库,例如pygame的。 There, you could use the music module and it's set_pos function or use the Sound class to access the raw audio data and cut it like you proposed in your question. 在那里,您可以使用音乐模块及其set_pos函数 ,也可以使用Sound类访问原始音频数据并按照问题中的建议进行剪切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM