2017-02-11 57 views
0

我有以下代碼可生成特定頻率的正弦波並使用pyaudio播放它。我想對其進行更改,以便僅在左側或僅在右側揚聲器通道上生成音頻。我將如何做到這一點?僅在一個通道上生成音頻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() 

回答

0

首先,你應該改變channels=1channels=2。那麼你應該修改你的play_tone函數,使它產生立體聲信號,而不是單聲道。通常情況下,您應該按照以下模式交織左右聲道的樣本:LRLRLRLRLRLR...

由於您需要通過單通道播放聲音,因此只需將樣本的左側或右側組成部分置零即可。