Python 3 和 mpg321 格式
Python 3 and mpg321 formating
我在使用 mpg321 播放随机声音时遇到了一些问题。
首先,我列出了所有声音,并将长度存储在一个变量中,然后创建一个介于 0 和该列表长度之间的随机数。我的问题是我不知道如何将它添加到文件路径 os.system() 内的字符串中。
sounds = os.listdir('./sounds/') # creates list of all sound names
totalSounds = len(sounds)
sound_number = random.randint(0, len(sounds))
next_sound = str(sounds[sound_number])
soundPlaying = True
os.system('mpg321 ./sounds/%s') % next_sound
soundPlaying = False
我试过使用 %s 并将变量放在 ./sounds/ 之后,但我收到一个语法错误,说 os.system() 只接受一个参数。
感谢任何帮助。
问题是您需要对字符串进行字符串格式化,而不是对函数调用
os.system('mpg321 ./sounds/%s'%next_sound)
对了,我会用subprocess,它提供的API比os.system帅多了! (https://docs.python.org/3/library/subprocess.html#subprocess.call)
import subprocess
subprocess.call(["mpg321", "./sounds/%s" % next_sound])
我在使用 mpg321 播放随机声音时遇到了一些问题。 首先,我列出了所有声音,并将长度存储在一个变量中,然后创建一个介于 0 和该列表长度之间的随机数。我的问题是我不知道如何将它添加到文件路径 os.system() 内的字符串中。
sounds = os.listdir('./sounds/') # creates list of all sound names
totalSounds = len(sounds)
sound_number = random.randint(0, len(sounds))
next_sound = str(sounds[sound_number])
soundPlaying = True
os.system('mpg321 ./sounds/%s') % next_sound
soundPlaying = False
我试过使用 %s 并将变量放在 ./sounds/ 之后,但我收到一个语法错误,说 os.system() 只接受一个参数。
感谢任何帮助。
问题是您需要对字符串进行字符串格式化,而不是对函数调用
os.system('mpg321 ./sounds/%s'%next_sound)
对了,我会用subprocess,它提供的API比os.system帅多了! (https://docs.python.org/3/library/subprocess.html#subprocess.call)
import subprocess
subprocess.call(["mpg321", "./sounds/%s" % next_sound])