简体   繁体   English

Pygame.mixer.sound的声音持续时间不够准确

[英]Sound duration isn't accurate enough with Pygame.mixer.sound

I want to generate a series of audio cues at specific frequency and duration for my neuroscience research. 我想为神经科学研究提供一系列特定频率和持续时间的音频提示。 After some googling, I find a Python module called Pygame that seems able to get the job done. 经过一番谷歌搜索后,我发现一个名为Pygame的Python模块似乎可以完成工作。

sound = pygame.sndarray.make_sound(sample_array)   #sample_array is a one-second sine wave I created
sound.play(maxtime = 100)   #play the sample_array for 100ms
pygame.time.delay(1000)     #pause for 1000ms

I run these code in a loop for many times. 我多次循环运行这些代码。 However, there is a small but noticeable difference in length of the sounds. 但是,声音的长度存在微小但明显的差异。 I recorded the sound with my phone, and analyzed the signal in Matlab. 我用手机记录了声音,并在Matlab中分析了信号。 Some of the pulses last for as long as 180ms, some short ones last only 80ms, while they should all last 100ms in theory. 有些脉冲持续时间长达180毫秒,一些短脉冲持续时间仅80毫秒,而理论上它们应全部持续100毫秒。

This kind of variation is too big for my application. 对于我的应用而言,这种变化太大。 Is there anything I can do to improve it? 我有什么可以改善的吗? Or it'll also be great if someone can confirm that this kind of precision is beyond Pygame's capacity, and maybe suggest another library to use. 或者,如果有人可以确认这种精度超出了Pygame的能力,并且可能建议使用另一个库,那也将很棒。

It looks like this question doesn't attract much attention :( 看来这个问题没有引起太多关注:(

I'm posting my workaround here in case someone wants to know. 如果有人想知道,我会在这里发布我的解决方法。 If I use sound.play(maxtime = 100) , or sound.play(-1) then time.delay(100) , the actual duration of the sound is never precisely 100ms. 如果我使用sound.play(maxtime = 100)sound.play(-1)然后使用time.delay(100) ,则声音的实际持续时间永远不会精确地为100ms。 My workaround is to generate a wav file beforehand which has exactly the length I need, and play this wav file. 我的解决方法是事先生成一个wav文件,该文件恰好具有我所需的长度,然后播放该wav文件。

sound = pygame.mixer.Sound("foo.wav")
sound.play()

It's not the best fix but this works for me. 这不是最好的解决方法,但这对我有用。

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

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