在连续循环中播放随机声音但两次不相同
Playing a random sound but not the same twice in a row loop
是否可以播放1、2、3或4这样的声音。虽然不是连续播放两次相同的声音,但它仍然可以在整体池中吗?
random.choice
将继续循环,但可以连续选择相同的两次。
但我似乎无法让 random.shuffle
循环?
while True:
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3",]
play = random.shuffle(sounds)
playsound(play)
为此,您需要创建一个 if 语句来检查前一个数字是否等于当前项目。为此,您需要添加此内容。
if play != previous:
playsound(play)
previous = play
您可以从列表中随机选择一个声音,不包括最后一个。然后将您选择的声音移动到列表的最后一个位置。
import random
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3"]
while True:
i = random.randrange(len(sounds)-1) # pick before last
sounds.append(sounds.pop(i)) # move it to end
print(sounds[-1]) # play selected
test1.mp3
test4.mp3
test3.mp3
test4.mp3
test1.mp3
test3.mp3
test4.mp3
test2.mp3
test1.mp3
test2.mp3
test4.mp3
...
这将使您永远不会连续两次听到相同的声音。
您可以通过仅从列表的前半部分选择声音来改进这一点。那么一个给定的声音永远不会在声音总数的一半内重复。
当您select播放一首歌曲时,从列表中删除最后一首歌曲。
import time
import random
random.seed(0)
def playsound(sound: str):
"""Define your function instead of printing these."""
print("start: " + sound)
time.sleep(1)
print(sound + " ended")
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3"]
prev = None # the last played song
while True:
nominees = sounds.copy()
if prev is not None:
nominees.remove(prev)
prev = random.choice(nominees)
playsound(prev)
是否可以播放1、2、3或4这样的声音。虽然不是连续播放两次相同的声音,但它仍然可以在整体池中吗?
random.choice
将继续循环,但可以连续选择相同的两次。
但我似乎无法让 random.shuffle
循环?
while True:
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3",]
play = random.shuffle(sounds)
playsound(play)
为此,您需要创建一个 if 语句来检查前一个数字是否等于当前项目。为此,您需要添加此内容。
if play != previous:
playsound(play)
previous = play
您可以从列表中随机选择一个声音,不包括最后一个。然后将您选择的声音移动到列表的最后一个位置。
import random
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3"]
while True:
i = random.randrange(len(sounds)-1) # pick before last
sounds.append(sounds.pop(i)) # move it to end
print(sounds[-1]) # play selected
test1.mp3
test4.mp3
test3.mp3
test4.mp3
test1.mp3
test3.mp3
test4.mp3
test2.mp3
test1.mp3
test2.mp3
test4.mp3
...
这将使您永远不会连续两次听到相同的声音。
您可以通过仅从列表的前半部分选择声音来改进这一点。那么一个给定的声音永远不会在声音总数的一半内重复。
当您select播放一首歌曲时,从列表中删除最后一首歌曲。
import time
import random
random.seed(0)
def playsound(sound: str):
"""Define your function instead of printing these."""
print("start: " + sound)
time.sleep(1)
print(sound + " ended")
sounds = ["test1.mp3", "test2.mp3", "test3.mp3", "test4.mp3"]
prev = None # the last played song
while True:
nominees = sounds.copy()
if prev is not None:
nominees.remove(prev)
prev = random.choice(nominees)
playsound(prev)