简体   繁体   English

Python - 如何在不互相干扰的情况下多次播放相同的声音?

[英]Python - How can I play the same sound multiple times without them interrupting each other?

I need to make a program where an audio file will play and halfway through the duration of the audio file the file will be played again but it won't cut off the one that isn't finished yet so the same file will be playing two times at once just with different start times我需要制作一个程序,在其中播放音频文件,并且在音频文件的持续时间中途将再次播放该文件,但它不会切断尚未完成的文件,因此同一个文件将播放两个一次只用不同的开始时间

I've tried using multiple libraries like pygame, winsound, and pyglet but as far as I can tell none of them allow this.我试过使用多个库,如 pygame、winsound 和 pyglet,但据我所知,它们都不允许这样做。

Edit: Ive tried using pygame again but it doesnt sound right.编辑:我再次尝试使用 pygame,但听起来不对。 I think its because of a delay with pygame我认为这是因为 pygame 的延迟

import pygame
import time
import threading

pygame.mixer.pre_init(frequency=44100)
pygame.mixer.init()

sound1 = pygame.mixer.Sound("Assets\\Blip.wav")
sound2 = pygame.mixer.Sound("Assets\\Blip.wav")
print(sound1.get_length())
half = 0.141/2

def play(ch,sound):
    pygame.mixer.Channel(ch).play(sound,loops=-1)

time.sleep(5)
t1 = threading.Thread(target=play,args=(0,sound1,))
t1.start()
time.sleep(half)
play(1,sound2,)

simpleaudio support concurrent playback of audio. simpleaudio支持音频的并发播放。 We use pydub for easy access to Audio segment length (although you can get same from simple audio with some effort).我们使用pydub来轻松访问音频段长度(尽管您可以通过一些努力从简单的音频中获得相同的长度)。 And pydub also can play simple audio (that gives us concurrent playback) using pydub.playback._play_with_simpleaudio() which makes code easier. pydub 还可以使用pydub.playback._play_with_simpleaudio()播放简单的音频(这使我们可以同时播放 ,这使代码更容易。

Here's an working example.这是一个工作示例。 I took two different audio files to check/illustrate that 2nd audio segment starts after first one is done halfway.我拿了两个不同的音频文件来检查/说明第二个音频片段在第一个音频片段中途完成后开始。

#!/usr/local/bin/python3

from pydub import AudioSegment
from pydub.playback import _play_with_simpleaudio

import threading
import time

def play(sound):
    play_obj = _play_with_simpleaudio(sound)

sound1 = AudioSegment.from_wav("Audio_1.wav")
sound2 = AudioSegment.from_wav("Audio_2.wav")

half = sound1.duration_seconds /2
t1 = threading.Thread(target=play,args=(sound1,))
t1.start()
time.sleep(half)
play(sound2)
time.sleep(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM