Python Raspberry Pi播放音乐

时间:2018-08-01 11:47:05

标签: python raspberry-pi distance volume playback

我正在运行一个脚本,该脚本从GPIO读取HC-SR04传感器的距离。计划是根据当前的距离输出来调节音乐输出(mp3文件)的音量。 由于脚本在Raspberry Pi上运行,因此Python版本是2.7.13。

这是当前脚本:

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)

如何在连续运行的Python脚本中运行mp3文件并调节音量?

1 个答案:

答案 0 :(得分:0)

要播放音频(.mp3)文件,您可以为python3安装sudo pip3 install playsound-(对于python2 sudo pip2 install playsound-),然后必须安装以下代码:

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

谢谢