-1

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?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
NicoF.
  • 26
  • 1
  • 6
  • `sudo apt-get install python3` and you have Python3 on your RasPi. – Adrian W Aug 01 '18 at 12:00
  • Python2 is at [end of life](https://stackoverflow.com/q/4836375). [Not so soon](https://pythonclock.org/) though, but anyway I would not recommend to begin a new project in Python2 unless forced to use that version. I just wanted to say that using a RasPi is nothing that forces you to use Python2. – Adrian W Aug 02 '18 at 16:13
  • I have python and python3 on my Raspberry, I'm not quite sure which Version my python IDLE is even using. I'm pretty new to python programming. – NicoF. Aug 03 '18 at 10:44

1 Answers1

0

For playing an audio(.mp3) file you can install sudo pip3 install playsound-for python3 sudo pip2 install playsound- for python2, then you have to so the following code:

from playsound import playsound
playsound(path of the audio file)

Thanks