使用Pyaudio在数组中播放波形数据

时间:2015-09-23 12:47:27

标签: python numpy pyaudio

我试图定义一个类,除其他外,它将波形文件读入一个numpy数组,然后播放它。看起来回调函数只被调用一次,所以我猜测用什么机制来保持流"活跃的没有工作?

有没有人成功完成过这项工作?

class asoa_io:

  def write_callback(self, in_data, frame_count, time_info, status):
    print "Frame count is " + str(frame_count)
    list_data = self.template_wave[self.template_idx:(self.template_idx+frame_count) - 1]
    data = list_data.tobytes()
    print repr(data)
    self.template_idx += frame_count
    return (data, pyaudio.paContinue)


  def read_callback(self, in_data, frame_count, time_info, status):
    self.signal += in_data  # This has the incoming signal as a list of frames.
    return (in_data, pyaudio.paContinue)

  """ Synthesize the speech and do any preprocessing.
  Note that we want to use the kal_diphone voice for synthesis.
  """
  def __init__(self, text_string):
    temp_fd, template_file = tempfile.mkstemp()
    string_file = tempfile.NamedTemporaryFile()


    string_file.write(text_string)
    string_file.flush()


    if (subprocess.call([PATH_TO_TEXT2WAVE, string_file.name, "-o", template_file]) > 0):
        print "Error running text2wave"

    string_file.close()


    self.template_rate, self.template_wave = scipy.io.wavfile.read(template_file)
    self.template_length = len(self.template_wave)
    self.template_framesize = 100

    self.pa = pyaudio.PyAudio()
#        self.input_stream =     self.pa.open(format=pyaudio.get_format_from_width(2),
#                                    channels=1, rate = self.template_rate, input=True,
#                                    stream_callback = self.read_callback)
    self.output_stream = self.pa.open(format=pyaudio.get_format_from_width(2),
                                 channels=1, rate = self.template_rate, output=True,
                                 stream_callback = self.write_callback)

    self.template_idx = 0
    self.signal = []


  def start_speech(self):
    self.output_stream.start_stream()
#        self.input_stream.start_stream()
    while self.output_stream.is_active():
        time.sleep(0.1)
    time.sleep(10)

  def stop(self):
    self.output_stream.stop_stream()
    self.input_stream.stop_stream()
    self.output_stream.close()
    self.input_stream.close()
    self.pa.terminate()

为了它的价值,我从pyaudio文档站点复制了示例回调代码,并用它来播放正在读取的wave文件;工作得很好。第一个1024字节也看起来正确。

感谢任何人的帮助!

0 个答案:

没有答案