【问题标题】:Playing a random sound but not the same twice in a row loop在连续循环中播放随机声音但不一样两次
【发布时间】:2022-01-28 16:24:04
【问题描述】:

是否可以播放 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)

【问题讨论】:

  • 只需将您使用过的那些存储在一个数组中,然后在您的 while 循环中检查它。
  • 将生成的播放存储在一个列表中,在生成下一个项目时,检查它是否存在于播放列表中。

标签: python random


【解决方案1】:

您可以从列表中随机选择一个声音,不包括最后一个。然后将您选择的声音移动到列表中的最后一个位置。

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
...

这将使您永远不会连续两次听到相同的声音。

您可以通过仅从列表的前半部分中选择声音来改进这一点。那么一个给定的声音将永远不会在声音总数的一半内重复。

【讨论】:

    【解决方案2】:

    为此,您需要创建一个 if 语句来检查前一个数字是否 = 当前项目。为此,您需要添加它。

    if play != previous:
        playsound(play)
        previous = play
    

    【讨论】:

      【解决方案3】:

      当您选择要播放的歌曲时,从列表中删除最后一首歌曲。

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多