0

Im having an Airplay setup on my RasPi2 so i can play Music over wifi to my Raspberry Pi which is plugged in to my speakers (The software is called "shairplay"). Now i want to control some LED strips in sync with the audio amplitude that is currently played.

So my Question is: Is there any way i can get the current sound Amplitude of the played sound from ALSA? (preferable in Python)

Bauer Marius
  • 170
  • 1
  • 12

2 Answers2

0

Yes actually, there is. You can manually set the volume in the shell, but using the OS module in python you can control it in python. Why is this important? Because you can use variables. You can buy Adafruit's LED strips and use if statements (based on the variable you set the volume to). An example code would be

import os
fubar = #volume here
os.system('amixer cset numid=1 -- ' + fubar)
if fubar > #whatever volume you want:
   #LED strip code here

There is also a tutorial on Adafruit to do just that! Happy programming!

Will4cat
  • 46
  • 4
  • i dont get it. numid=1,iface=MIXER,name='PCM Playback Volume' ; type=INTEGER,access=rw---R--,values=1,min=-10239,max=400,step=0 : values=0 | dBscale-min=-102.39dB,step=0.01dB,mute=1 0 – Bauer Marius Oct 23 '16 at 20:46
  • i dont get it `os.system('amixer cset numid=1 -- ' + fubar)` does return `numid=1,iface=MIXER,name='PCM Playback Volume' ; type=INTEGER,access=rw---R--,values=1,min=-10239,max=400,step=0 : values=0 | dBscale-min=-102.39dB,step=0.01dB,mute=1 0 ` which of those values represent my actual amplitude? – Bauer Marius Oct 23 '16 at 20:49
  • All you have to do is put an integer value after amixer cset numed=1 – Will4cat Nov 12 '16 at 00:50
0

This example uses maximum amplitude of the sound to detect noise using python. The same concept can be used to plot your amplitudes,

sox.sh

#!/bin/sh
filename=$1
duration=$2
arecord -q -f cd -d $duration -t raw | lame -r - $filename
sox $filename -n stat 2>&1 | sed -n 's#^Maximum amplitude:[^0-9]*\([0-9.]*\)$#\1#p'

soundcapture.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import os
import subprocess
import sys
import re
import time

def main(args=None):

    try:
        while True:
            filename = time.strftime("%Y%m%d%H%M%S") + ".wav"
            proc = subprocess.Popen(['sh','sox.sh', filename, '5' ], stdout=subprocess.PIPE)
            result,errors = proc.communicate()
            amplitude=float(result)
            print amplitude
            if amplitude > 0.15:
                print 'Sound detected'
                #os.rename(filename, "data/" + filename)
            else:
                print 'No sound detected'
                #os.remove(filename)
    except KeyboardInterrupt:
        print('')
    finally:
        print('Program over')

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]) or 0)

Please checkout its github page for more details.

Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110