microsoft / wslg

Enabling the Windows Subsystem for Linux to include support for Wayland and X server related scenarios
MIT License
9.9k stars 296 forks source link

Crackly Sound #1228

Closed tom-huntington closed 2 months ago

tom-huntington commented 2 months ago

Windows build number:

10.0.22000.2538

Your Distribution version:

Ubuntu 22.04

Your WSL versions:

WSL version: 2.1.5.0 Kernel version: 5.15.146.1-2 WSLg version: 1.0.60 MSRDC version: 1.2.5105 Direct3D version: 1.611.1-81528511 DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp Windows version: 10.0.22000.2538

Steps to reproduce:

import numpy as np
import sounddevice as sd

duration = 2.0
frequency = 440.0
sample_rate = 44100 

t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
audio = np.sin(2 * np.pi * frequency * t)

sd.play(audio, samplerate=sample_rate)
sd.wait()

Actual behavior:

The first time I play the sound, it is clean. Subsequent, attempts produce a crackling sound:

If I wsl --shutdown the first time, the sound is clean, subsequent sounds are still crackly.

https://github.com/microsoft/wslg/assets/55266932/f12ffde6-abeb-4623-95ec-35a5e0fd972e

Edit

As I was writing this, I realised since wslg routes everything through pulse audio I should use a pulseaudio api which produced an acceptable result:

import numpy as np
import pasimple

duration = 2.0  # seconds
frequency = 440.0  # Hz (A4 note)
sample_rate = 44100  # samples per second
amplitude = 32767  # maximum amplitude for a 16-bit PCM

t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
sine_wave = amplitude * np.sin(2 * np.pi * frequency * t)
audio_data = np.int16(sine_wave)

format = pasimple.PA_SAMPLE_S16LE  # Little-endian 16-bit
channels = 1 

with pasimple.PaSimple(pasimple.PA_STREAM_PLAYBACK, format, channels, sample_rate) as pa:
    pa.write(audio_data.tobytes())
    pa.drain()

https://github.com/microsoft/wslg/assets/55266932/1744bf18-4f76-4446-8068-5b9fa648896c