From d23b26b2e59c491ba7a3a259d9cb170ddbe083ad Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Thu, 1 Feb 2024 21:27:00 +0100 Subject: [PATCH] isine example: fix stereo handling (#42) while it's usually not actually necessary to generate a stereo signal (alsa's default plughw device will happily duplicate it for us), we still do it for demo purposes, just because. a more realistic demo would actually use numpy, as that's what the library will most likely be used with, but anyway. --- isine.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/isine.py b/isine.py index 50c8854..c792818 100644 --- a/isine.py +++ b/isine.py @@ -18,12 +18,13 @@ else: from math import pi, sin, ceil import struct +import itertools import alsaaudio sampling_rate = 48000 format = alsaaudio.PCM_FORMAT_S16_LE -framesize = 2 # bytes per frame for the values above +pack_format = 'h' # short int, matching S16 channels = 2 def nearest_frequency(frequency): @@ -47,7 +48,10 @@ def generate(frequency, duration = 0.125): sine = [ int(32767 * sin(2 * pi * frequency * i / sampling_rate)) \ for i in range(size)] - return struct.pack('%dh' % size, *sine) + if channels > 1: + sine = list(itertools.chain.from_iterable(itertools.repeat(x, channels) for x in sine)) + + return struct.pack(str(size * channels) + pack_format, *sine) class SinePlayer(Thread):