数组的项目格式不支持'd'

时间:2018-04-08 19:35:33

标签: python arrays numpy audio pygame

我正在使用 pygame 以特定频率播放声音,并且工作正常,直到我尝试使用预先生成的数组播放方波。

我正在使用scipy和numpy,我的代码的相关片段如下:

pygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12)

def play(sample_wave, ms):
    sound = pygame.sndarray.make_sound(sample_wave)
    sound.play(-1)
    pygame.time.delay(ms)
    sound.stop()

def square_wave(hz, peak, duty_cycle=.5, n_sample=44100):
    t = numpy.linspace(0, 1, 500 * 440/hz, endpoint=False)
    wave = scipy.signal.square(2 * numpy.pi * 5 * numpy.sin(t), duty=duty_cycle)
    wave = numpy.resize(wave, (n_samples,))
    return (peak / 2 * wave.astype(numpy.int16))

play(square_wave(440, 4096), 1000)

但是,当我运行此代码时,我收到有关生成的数组的错误:

Traceback (most recent call last):
  File "/Users/foo/Desktop/freq.py", line 77, in <module>
    play(square_wv(440, 254),1000)
  File "/Users/bar/Desktop/freq.py", line 9, in play
    sound = pygame.sndarray.make_sound(sample_wave)
  File "/Users/baz/Library/Python/3.6/lib/python/site-packages/pygame/sndarray.py", line 80, in make_sound
    return numpysnd.make_sound (array)
  File "/Users/foobar/Library/Python/3.6/lib/python/site-packages/pygame/_numpysndarray.py", line 75, in make_sound
    return mixer.Sound (array=array)
ValueError: Array has unsupported item format 'd'

此错误的原因是什么?如果有人碰巧知道,我会非常感激,因为它似乎在整个网络上都没有记录。

更新:

https://gist.github.com/ohsqueezy/6540433似乎有另一种产生方波的方法。任何人都可以解释为什么这个代码恰好工作而上面的例子没有?

0 个答案:

没有答案