简体   繁体   中英

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)

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM