Pyaudio / Numpy 串联音符仅扩展第一个音符

Pyaudio / Numpy Concatenated Notes Merely Extend the First Note

我正在尝试使用 pyaudio 生成我自己的笔记,但我 运行 陷入了初学者的错误。我可以生成纯 sin wav 音调并按顺序播放它们,但是如果我尝试将它们连接起来,我不会连续得到三个音符,我得到的是原始音符播放的三倍长。

import numpy as np
import pyaudio

def play_note(note):
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                      channels=1,
                      rate=44100,
                      output=True)
    stream.write(np.asarray(note, dtype=np.float32))
    stream.stop_stream()
    stream.close()
    p.terminate()

sampling_rate = 44100
seconds = 1
x = np.arange(sampling_rate * seconds)

freqs = [440,660,880]

notes = []

for freq in freqs:
    note = 100*np.sin(2 * np.pi * freq * x /sampling_rate)
    notes.append(note)

# This is the behavior I want
for note in notes:
    play_note(note)

# I would expect this to behave similarly, but without the gaps. It doesn't.
note = np.concatenate(notes)
play_note(note)

我得到与 pyaudio 0.2.11 相同的结果(运行 on Mac OS 10.12.6)。我能够通过将参数 frames_per_buffer=1 添加到 p.open() 并将 num_frames=len(note) 添加到 stream.write():

来修复它
def play_note(note):
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                      channels=1,
                      rate=44100,
                      output=True,
                      frames_per_buffer=1)
    stream.write(np.asarray(note, dtype=np.float32), num_frames=len(note))
    stream.stop_stream()
    stream.close()
    p.terminate()

我还没有进一步调查来回答为什么原始版本不起作用或为什么此更改修复了它。也许pyaudio大师会给出更彻底的答案。