pythonaudioraspberry-piraspberry-pi2airplay

Get Audio Amplitude from ALSA Raspberry Pi


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)


Solution

  • 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.