[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Creating a stereo sound from an array doubles frequency



Hi list,

I'm having trouble playing sounds (generated from arrays) as stereo
sounds. Creating a sound and copying it to two channels seems to
double the frequency.

The following script (see also here: http://pastebin.com/qqZbJavf )
should make it more clear. It constructs a simple 400Hz sine wave and
plays it as a mono sound (nchannels = 1) or duplicates the array and
plays it as a stereo sound (nchannels = 2). In the second case,
however, the tone that is played is an 800Hz tone instead of a 400Hz
one... This seems not to happen on Windows, I encountered the problem
on ArchLinux and Ubuntu 11.10 (both having pygame 1.9.1).

import numpy as np
import pygame as pg
import time

frequency, samplerate, duration = 400, 44100, 20000
nchannels = 1 # change to 2 for stereo
pg.mixer.pre_init(channels=nchannels, frequency=samplerate)
pg.init()

sinusoid = (2**15 - 1) * np.sin(2.0 * np.pi * frequency * \
                   np.arange(0, duration) / float(samplerate))
samples = np.array(sinusoid, dtype=np.int16)
if nchannels > 1: #copy mono signal to two channels
       samples = np.tile(samples, (nchannels, 1)).T
sound = pg.sndarray.make_sound(samples)
sound.play()

time.sleep(duration/float(samplerate))