I have a script running which reads out the distance of a HC-SR04 Sensor from my GPIOs. The plan is to regulate the volume of a music output (mp3 file) depending on the current distance output. Since the script is running on a Raspberry Pi the Python version is 2.7.13.
This is the current script:
import RPi.GPIO as GPIO
import time
import signal
import sys
# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)
# set GPIO Pins
pinTrigger = 18
pinTrigger2 = 17
pinTrigger3 = 27
pinEcho = 24
pinEcho2 = 23
pinEcho3 = 25
def close(signal, frame):
print("\nTurning off ultrasonic distance detection...\n")
GPIO.cleanup()
sys.exit(0)
def playMusic(distance):
subProcess.call(["/usr/bin/mpg321","0001.mpr.mp3"])
signal.signal(signal.SIGINT, close)
# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)
#GPIO.setup(pinTrigger2, GPIO.OUT)
#GPIO.setup(pinEcho2, GPIO.IN)
#GPIO.setup(pinTrigger3, GPIO.OUT)
#GPIO.setup(pinEcho3, GPIO.IN)
while True:
# set Trigger to HIGH
GPIO.output(pinTrigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(pinTrigger, False)
startTime = time.time()
stopTime = time.time()
#subProcess.call(["/usr/bin/mpg321","0001.mpr.mp3"])
# speichert die startzeit
while 0 == GPIO.input(pinEcho):
startTime = time.time()
# speichert die ankunftszeit
while 1 == GPIO.input(pinEcho):
stopTime = time.time()
# zeitunterschied zwischen ankunft und start
TimeElapsed = stopTime - startTime
# multipliziert mit der Schallgeschwindigkeit (34300 cm/s)
# und durch 2, weil der Schall hin und zurück geht
distance = (TimeElapsed * 34300) / 2
print ("Distance Sensor 1: %.1f cm" % distance)
time.sleep(1)
How can I run a mp3 file and regulate the volume in a continuously running Python script?