Python多线程 - 同时播放多个正弦波

时间:2016-07-11 08:42:42

标签: python multithreading

我想在给定的频率和持续时间内产生正弦波噪声。我希望在使用GUI时同时播放。

我已经创建了一个使用线程的类,但它似乎不起作用。我无法在调用.run()行的同时执行代码。例如,当运行以下代码时,print语句在声音完成后执行。

import pyaudio
import numpy as np
import threading

class WavePlayerLoop(threading.Thread) :
  """
  A simple class based on PyAudio to play sine wave at certain frequency.
  It's a threading class. You can play audio while your application
  continues to do stuff.
  """

  def __init__(self, freq=440., length=1., volume=0.5):
    threading.Thread.__init__(self)
    self.p = pyaudio.PyAudio()

    self.volume = volume     # range [0.0, 1.0]
    self.fs = 44100          # sampling rate, Hz, must be integer
    self.duration = length   # in seconds, may be float
    self.f = freq            # sine frequency, Hz, may be float

  def run(self) :
    """
    Just another name for self.start()
    """
    # generate samples, note conversion to float32 array
    self.samples = (np.sin(2*np.pi*np.arange(self.fs*self.duration)*self.f/self.fs)).astype(np.float32)

    # for paFloat32 sample values must be in range [-1.0, 1.0]
    self.stream = self.p.open(format=pyaudio.paFloat32,
                    channels=1,
                    rate=self.fs,
                    output=True)

    # play. May repeat with different volume values (if done interactively) 
    self.stream.write(self.volume*self.samples)

    self.stream.stop_stream()
    self.stream.close()

    self.p.terminate()

s = WavePlayerLoop(freq=440., length=10., volume=0.5)
s.run()
print 'this should print while there is a beep sound'

在其他代码可以执行的同时,我需要做什么才能让这个声音同时播放?

1 个答案:

答案 0 :(得分:1)

你好像完全正确。以下测试代码与您的代码完美配合。

objs = []
number_of_threads = 10

print 'Creating thread objects'
for i in range(number_of_threads):
    objs.append(WavePlayerLoop(freq=440 * i, length=10., volume=0.1 * i))

print 'Starting thread objects'
for i in range(number_of_threads):
    objs[i].start()

print 'Waiting for threads to finish'
for i in range(number_of_threads):
    objs[i].join()

print ('Finishing program')