0

So I've been trying to get into Python recently, and one thing that I really want to know is how do you make the speakers as an input device and in return output a number that shows the volume. For example:

0 if there's no video playing. and then 30-50 if it's a podcast. 70-90 if it's a firework show. And 100 if it's just a frequency.

Thank you to anyone that can help :)

  • this has some pointers of alternatives how to get audio: https://stackoverflow.com/questions/35344649/reading-input-sound-signal-using-python . it might be most robust to just use the native api of your operating system, are you on Windows, Linux or Mac .. or iOS or Android? – antont Jan 04 '20 at 06:23

1 Answers1

-1

What I think you are looking for is sound loopback, i.e. record the output of the sound device.

If you are on Windows there is a fork of PyAudio doing that: pyaudio_portaudio.

As the example on the project homepage shows it is as easy as this:

import pyaudio
p = pyaudio.PyAudio()
stream = p.open([...], as_loopback = True)

Then you just calculate the amplitude of the audio stream.

arghol
  • 745
  • 9
  • 21
  • So 'stream' is going to be the value of the sound? – MilkAndBanana Jan 04 '20 at 16:16
  • Exactly, `stream` will contain the actual sound samples according to parameters given to `open()`, e.g. 16 bit integers or floats. – arghol Jan 04 '20 at 16:24
  • So can I literally do: print(stream) in a while loop and it would print the volume? – MilkAndBanana Jan 11 '20 at 07:22
  • No, `stream` contains raw, [PCM encoded](https://en.wikipedia.org/wiki/Pulse-code_modulation) audio samples. The volume can be calculated from the samples in different ways. The peak value is just the maximum absolute value of an interval. Since audio can contain spurious high amplitude peaks that isn't a very good measure of the overall interval, it is often more useful to calculate the [root mean square](https://en.wikipedia.org/wiki/Root_mean_square) (a kind of mean value). – arghol Jan 11 '20 at 09:40
  • Sorry for the super late reply, I have just successfully installed Pyaudio, can you provide a formula that I can assign to a variable that equates to the volume. The wikipedia page was not exactly the most helpful thing I can get, so like can I just have a variable that outputs a number from 0-100 based on the volume? – MilkAndBanana Jan 21 '20 at 09:27