bastibe / SoundCard

A Pure-Python Real-Time Audio Library
https://soundcard.readthedocs.io
BSD 3-Clause "New" or "Revised" License
680 stars 69 forks source link

Playing continuously without using with construct #132

Closed RuABraun closed 3 years ago

RuABraun commented 3 years ago

Hi! I want to use soundcard to play sounds continuously, but without using the with speaker.player(...) as ... construct as the player/stream is meant to be part of a class.

I was hoping I could just call __enter__() to simulate being inside a with block, but playing sounds does not really work for some reason. Example code

import numpy as np
import soundcard as sc

spkr = sc.default_speaker()
a = np.random.randn(44100) / 100.
player = spkr.player(samplerate=44100, channels=1)
player.__enter__()
player.play(a)

The weird thing is if I add second player.play(a) call I get a sound, but that stops working if I shorten the length of the signal.

So I'm guessing there's some extra setup that needs to be done to play sounds, but I cannot figure out what it is?

RuABraun commented 3 years ago

It seems to be related to the blocksize ? If I set it smaller than the signal that part of the signal gets played.

Trying to see if I can manually drain the buffer.

RuABraun commented 3 years ago

I've also got multiprocessing going on, #96 relevant

edit: So I got it to work by importing soundcard inside the class/method.

Sometimes player.play() does not return immediately, instead taking as long as the sound to be played, why could this be?

RuABraun commented 3 years ago

I was doing too much work on the audio thread, and some processing I was doing was making it sound like there was a pause.

RuABraun commented 3 years ago

And my question about play() not returning immediately was answered very nicely here: https://bastibe.de/2017-06-27-audio-apis-pulseaudio.html