仅在一个频道pyaudio上生成音频

时间:2017-02-11 08:58:26

标签: python audio pyaudio

我有以下代码生成特定频率的sin波并使用pyaudio播放它。我想改变它,使得音频仅在左侧生成,或仅在右侧扬声器通道上生成。我该怎么做?

import math
import struct
import pyaudio

def play_tone(frequency, amplitude, duration, fs, stream):
    N = int(fs / frequency)
    T = int(frequency * duration)  # repeat for T cycles
    dt = 1.0 / fs
    # 1 cycle
    tone = (amplitude * math.sin(2 * math.pi * frequency * n * dt) for n in xrange(N))
    print type(tone)
    # todo: get the format from the stream; this assumes Float32
    data = ''.join(struct.pack('f', samp) for samp in tone)
    for n in xrange(T):
        stream.write(data)

fs = 48000
p = pyaudio.PyAudio()
stream = p.open(
   format=pyaudio.paFloat32,
   channels=1,
   rate=fs,
   output=True)

play_tone(200, 0.5, 0.75, fs, stream)

stream.close()
p.terminate()

1 个答案:

答案 0 :(得分:0)

首先,您应该将channels=1更改为channels=2。然后你应该修改你的play_tone函数,使其生成立体声信号而不是单声道。通常,您应按以下模式交错左右声道的样本:LRLRLRLRLRLR...

由于您需要通过单个通道播放声音,因此只需将零填充为样本的左侧或右侧组件。