python中的实时音频播放

时间:2018-10-14 12:18:22

标签: python pyaudio

我的任务是从弦的不同模型生成吉他般的声音。到目前为止,我已经编写了一个例程,可以在最初的n秒内建立声音,但是此后我遇到了麻烦。

建立声音然后播放声音会花费很多时间(最多10秒),而我最终将要求它是瞬时的。我正在寻找的是一个python库,它将允许我在播放缓冲区的同时向缓冲区添加音频。下面是代码的概述

  for t in range(2, duration * fs):
  curr_t = t%CHUNK
  prev_t = (t-1)%CHUNK
  if prev_t < curr_t:
    u_plus[curr_t] = OSD(u_plus[prev_t])
    u_minus[curr_t] = inv_OSD(u_minus[prev_t])
    u_plus[curr_t][0] = -1.0*u_minus[curr_t][0]
    # u_minus[curr_t][N-1] = -1.0*end_gain*u_plus[curr_t][N-1]
    if curr_t%2 == 0:
      samp_sig = u_plus[(slice(0,curr_t), N-1)]
      samp_sig_filt = scisig.filtfilt(b, a, samp_sig, padlen=0)
      u_minus[(slice(0,curr_t), N-1)] = -1.0*end_gain*samp_sig_filt
    else:
      u_minus[curr_t][N-1] = -1.0*end_gain*u_plus[curr_t][N-1]

    u_net[curr_t] = u_plus[curr_t] + u_minus[curr_t]
  else:
    disp_fft = freq_trans(u_net, fs)
    norm_press_t = pressure_wave_gen(disp_fft, u_net, fs, CHUNK)
    play_audio = np.append(play_audio,norm_press_t)
    def callback(in_data, frame_count, time_info, status):
      data = play_audio.astype(np.float32).tostring()
      return (data, pyaudio.paContinue) 

    stream = p.open(format=pyaudio.paFloat32,
                    channels=1,
                    rate = fs,
                    frames_per_buffer = CHUNK,
                    output=True,
                    stream_callback = callback
                    )
    stream.start_stream()

    u_net = np.zeros([CHUNK,N]).astype(np.float)
    u_buffer_plus = u_plus[CHUNK-1]
    u_buffer_minus = u_minus[CHUNK-1]
    u_plus = np.zeros([CHUNK,N]).astype(np.float)                                                   
    u_minus = np.zeros([CHUNK,N]).astype(np.float)
    u_plus[0] = OSD(u_buffer_plus)
    u_minus[0] = inv_OSD(u_buffer_minus)
    u_plus[0][0] = -1.0*u_minus[0][0]
    u_minus[0][N-1] = -1.0*end_gain*u_plus[0][N-1]
    u_net[0] = u_plus[0] + u_minus[0]

因此,我打算执行的代码是每次计算固定数量的u_net时,在队列播放当前音频时将其添加到队列中,以加快声音合成。但是目前,只要音频和剪辑非常失真,我就会遇到欠载错误。我正在使用pyaudio,但如果还有另一个更适合此目的的软件包,请告诉我

0 个答案:

没有答案