Twingemios
Twingemios

Reputation: 61

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.

Edit: Ive tried using pygame again but it doesnt sound right. I think its because of a delay with 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,)

Upvotes: 4

Views: 1738

Answers (1)

Anil_M
Anil_M

Reputation: 11453

simpleaudio support concurrent playback of audio. We use pydub for easy access to Audio segment length (although you can get same from simple audio with some effort). And pydub also can play simple audio (that gives us concurrent playback) using pydub.playback._play_with_simpleaudio() which makes code easier.

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)

Upvotes: 3

Related Questions