Reputation: 21
I have the following code that generates a sin wave of a specific frequency and plays it using pyaudio. I would like to change it such that the audio is only generated on the left, or only on the right speaker channel. How would I do this?
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()
Upvotes: 2
Views: 1895
Reputation: 429
At first you should change channels=1
to channels=2
. Then you should modify your play_tone
function to make it generate stereo signal instead mono. Usually you should interleave samples for left and right channels in following pattern: LRLRLRLRLRLR...
Since you need to play sound via single channel then just put zeros for either left or right component of sample.
Upvotes: 1