spatialaudio / python-sounddevice

:sound: Play and Record Sound with Python :snake:
https://python-sounddevice.readthedocs.io/
MIT License
980 stars 145 forks source link

How to get volume level of playing sound with RawOutputStream ? #497

Closed JamesZBL closed 8 months ago

JamesZBL commented 8 months ago

I use np.linalg.norm(data), but It returns 15000 to 18000 when I use it with RawOutputStream. How can I get the volume level? Or should I use OutputStream alternatively? Is there any examples ? I just find only RawOutputStream example here:[https://python-sounddevice.readthedocs.io/en/0.3.14/examples.html#play-a-very-long-sound-file].

Apppreciated for any help.

mgeier commented 8 months ago

The term "level" is a bit ambiguous, so it would help if you could clarify (mathematically) what exactly you need.

But either way, you should note that the outdata argument of the callback function passed to the RawOutputStream constructor (https://python-sounddevice.readthedocs.io/en/0.4.6/api/raw-streams.html#sounddevice.RawOutputStream) will be a plain Python buffer. This means it contains just a sequence of bytes. Those bytes have to be converted to meaningful numbers before you can do mathematical operations on them. If you pass the bytes directly to something like np.linalg.norm(), the result is most likely not what you expect.

You should note that the "raw" streams (like RawOutputStream) are specifically made for the case where you don't want to (or cannot) use NumPy. If you use NumPy anyway for your calculations, you might just as well use the non-raw streams (like OutputStream), where your callback will directly receive NumPy arrays, so you don't have to worry about the conversion from bytes to numbers. You only have to choose the dtype you want to use (by default float32).

JamesZBL commented 8 months ago

Is the any example for Play file Using OutputStream? I only find the example for Play signal Using OutputStream.

JamesZBL commented 8 months ago

The example for Playing file is RawOutputStream. It's different.

mgeier commented 8 months ago

Is the any example for Play file Using OutputStream?

The examples are there: https://github.com/spatialaudio/python-sounddevice/tree/master/examples And the can also be seen here: https://python-sounddevice.readthedocs.io/en/0.4.6/examples.html

If I counted correctly, 4 of them use OutputStream and 2 of them use RawOutputStream.

Feel free to use GitHub's "search" function at the top of this page.