Regarding inability of Python Module Winsound to produce beep in decimal frequency

Eryk Sun eryksun at gmail.com
Mon Aug 16 21:43:11 EDT 2021


On 8/16/21, Roel Schroeven <roel at roelschroeven.net> wrote:
>
> We're not necessarily talking about the PC speaker here: (almost) all
> computers these days have sound cards (mostly integrated on the
> motherboard) that are much more capable than those one-bit PC speakers.

Yes, the PC speaker beep does not get used in Windows 7+. The beep
device object is retained for compatibility, but it redirects the
request to a task in the user's session (which could be a remote
desktop session) that generates a WAV buffer in memory and plays it
via PlaySound(). You can do this yourself if you need a more precise
frequency. For example:

    import io
    import math
    import wave
    import winsound

    def beep(frequency, duration):
        '''Play a beep at frequency (hertz) for duration (milliseconds).'''
        fs = 48000
        f = 2 * math.pi * frequency / fs
        n = round(duration * fs / 1000)
        b = io.BytesIO()
        w = wave.Wave_write(b)
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(fs)
        w.writeframes(b''.join(round(32767 * math.sin(f*i)).to_bytes(
                                2, 'little', signed=True) for i in range(n)))
        w.close()
        winsound.PlaySound(b.getbuffer(), winsound.SND_MEMORY)


Play a beep at 277.1826 Hz for one second:

    beep(277.1826, 1000)

I'm tone deaf, I suppose, since I need a difference of about 3 cycles
to perceive it, let alone a fraction of a cycle.


More information about the Python-list mailing list