File size: 1,276 Bytes
78cb487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import numpy as np
import sounddevice as sd
import time


def play_audio(audio_data: np.ndarray, sample_rate: int = 24000):
    """
    Play audio directly using sounddevice.

    Args:
        audio_data (np.ndarray): The audio data to play.
        sample_rate (int, optional): The sample rate of the audio data. Defaults to 24000.
    """
    try:
        sd.play(audio_data, sample_rate)
        sd.wait()
    except Exception as e:
        print(f"Error playing audio: {str(e)}")


def stream_audio_chunks(
    audio_chunks: list, sample_rate: int = 24000, pause_duration: float = 0.2
):
    """
    Stream audio chunks one after another with a small pause between them.

    Args:
        audio_chunks (list): A list of audio chunks to play.
        sample_rate (int, optional): The sample rate of the audio data. Defaults to 24000.
        pause_duration (float, optional): The duration of the pause between chunks in seconds. Defaults to 0.2.
    """
    try:
        for chunk in audio_chunks:
            if len(chunk) == 0:
                continue
            sd.play(chunk, sample_rate)
            sd.wait()
            time.sleep(pause_duration)
    except Exception as e:
        print(f"Error streaming audio chunks: {str(e)}")
    finally:
        sd.stop()