gpt4 book ai didi

php - 如何仅在从 mysql 数据库中选择一行时执行 python 代码块

转载 作者:行者123 更新时间:2023-11-29 15:48:50 25 4
gpt4 key购买 nike

我用Python、运动传感器和树莓派构建了一套音乐楼梯,以及一个网络应用程序,可以让你选择想要发出哪种类型的乐器声音。乐器的类型存储在 MySQL 数据库中,我已将该数据库连接到 python 代码(当光束被破坏时会发出声音)和一个 Web 应用程序,该应用程序允许用户从数据库中选择乐器类型。

我只是想知道是否有一种从 python 代码查询数据库的方法,这意味着只有当从数据库中选择一行时,才运行特定的代码块。

例如,有人在网络应用程序上单击“Drum”。乐器类型“Drum”选自MySQL数据库Drumsound.play() 应该在 python 代码上运行。

有什么办法可以在 python 上做到这一点吗?

这适用于运行 python 2.7、mySQLdb5 和 apache2 的树莓派 3。

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="*****",
pw="*****",
db="stairs"
)

cursor = mydb.cursor()
cursor.execute("SELECT variableValue FROM stairs WHERE variableValue =
'instrumentType'")

import RPi.GPIO as GPIO # GPIO
import pygame.mixer # To make sound
pygame.mixer.init()

''' GPIO setup '''
GPIO.setmode(GPIO.BCM) # GPIO setmode
GPIO.setwarnings(False)

'''Define steps and pins here'''
step1 = 4


'''Motion sensor setup here'''
GPIO.setup(step1, GPIO.IN, GPIO.PUD_UP)


'''Piano files here'''
C1 = pygame.mixer.Sound("piano/C1.wav")


'''Drum files here'''
drum1 = pygame.mixer.Sound("drum/C1.wav")



def play(pin):
sound = sound_pins[pin]
print("Playing note from pin %s" % pin)
sound.play()

'''Dictionary of steps and sounds'''
sound_pins = {
step1: C1,
step2: D,
step3: E,
step4: F,
step5: G,
step6: A,
step7: B,
step8: C2,
}

for pin in sound_pins:
GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
GPIO.add_event_detect(pin, GPIO.RISING, play, 100)

最佳答案

您可以考虑使用python dictionary根据函数存储您的“仪器”类型。这允许您创建声音播放的乐器的映射。

您可能会问自己,“这听起来像是我希望我的数据库执行的操作?”。当您使用相同的 pygame.mixer.Sound("SomeWavePath") 时,您可以将乐器名称与其声音文件之间的关系存储在数据库本身中。这样,您只需添加到数据库即可扩展您的仪器选择。

我还建议您切换到 Python 3.x,因为 2.x 很快就会停止支持 ( https://pythonclock.org/ )。这还将使您能够访问新的语言功能和更广泛的库支持。

编辑:

例如,在数据库中存储“instrument<->wav_path”映射。

# Query executing obtains 'wav path' from 'instrument' primary key.
choice = cur.fetchone() # "piano/C1.wav"
sound_to_play = pygame.mixer.Sound(choice)

例如,将物体附着在您的乐器上

C1 = pygame.mixer.Sound("piano/C1.wav")
drum1 = pygame.mixer.Sound("drum/C1.wav")

instrument_dict = {
"piano": C1,
"drum": drum1
}

# Retrieve the sound to play
choice = cur.fetchone() # From our database, get 'drum' for example
sound_to_play = instrument_dict[ choice ]
# instrument_dict[ 'drum' ] => drum1 Sound Object.

然后:

sound_to_play.play()

关于php - 如何仅在从 mysql 数据库中选择一行时执行 python 代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56886092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com