10 Play Audio Files

From Waveshare Wiki
Jump to: navigation, search

Due to security reasons, you cannot directly access the audio device through JupyterLab (environment limitations). The code blocks provided here are not meant for user execution.

The code presented here is extracted from the product's main program, audio_ctrl.py. You can refer to this code to understand how the main program implements the functionality of playing audio files.

Audio-related Functionality in the Product Main Program

Inside the folder of the product's main program, there is a folder named "sounds", which contains many subfolders: connected, others, recv_new_cmd, robot_started, searching_for_target, target_detected, target_locked.

In the default program provided, only one audio file is placed in each of the connected and robot_started subfolders.

Once the robot's main program starts running, it will automatically play a random audio file from the robot_started folder.

When a client connects to this web application using a browser, a random audio file from the connected folder will be played automatically.

You can place custom audio files in these folders as voice packs to customize your product further.

import pygame  # Import the pygame library for audio playback
import random  # Import the random library for random selection of audio files
import yaml  # Import the yaml library for reading configuration files
import os  # Import the os library for file operations
import threading  # Import the threading library for multithreading

# Get the configuration file
curpath = os.path.realpath(__file__)
thisPath = os.path.dirname(curpath)
with open(thisPath + '/config.yaml', 'r') as yaml_file:
    config = yaml.safe_load(yaml_file)

# Initialize pygame.mixer and set the default volume for audio output
pygame.mixer.init()
pygame.mixer.music.set_volume(config['audio_config']['default_volume'])

# Create an event object for controlling audio playback
play_audio_event = threading.Event()

# Get the minimum time between plays from the configuration file
min_time_bewteen_play = config['audio_config']['min_time_bewteen_play']

# Define a function to play an audio file
def play_audio(input_audio_file):
    try:
        pygame.mixer.music.load(input_audio_file)  # Load the audio file
        pygame.mixer.music.play()  # Play the audio
    except:
        play_audio_event.clear()  # Clear the event in case of an error
        return
    while pygame.mixer.music.get_busy():  # Wait for the audio to finish playing
        pass
    time.sleep(min_time_bewteen_play)  # Wait for the minimum time between plays
    play_audio_event.clear()  # Clear the event

# Define a function to play a random audio file
def play_random_audio(input_dirname, force_flag):
    if play_audio_event.is_set() and not force_flag:
        return
    # Get all audio files in the specified directory
    audio_files = [f for f in os.listdir(current_path + "/sounds/" + input_dirname) if f.endswith((".mp3", ".wav"))]
    # Choose a random audio file from the list
    audio_file = random.choice(audio_files)
    play_audio_event.set()  # Set the event
    # Create a thread to play the audio
    audio_thread = threading.Thread(target=play_audio, args=(current_path + "/sounds/" + input_dirname + "/" + audio_file,))
    audio_thread.start()  # Start the thread

# Define a function to handle audio playback in a separate thread
def play_audio_thread(input_file):
    if play_audio_event.is_set():  # If the event is already set, return
        return
    play_audio_event.set()  # Set the event
    # Create a thread to play the audio
    audio_thread = threading.Thread(target=play_audio, args=(input_file,))
    audio_thread.start()  # Start the thread

# Define a function to play a specified audio file
def play_file(audio_file):
    audio_file = current_path + "/sounds/" + audio_file
    play_audio_thread(audio_file)

# Define a function to set the audio volume
def set_audio_volume(input_volume):
    input_volume = float(input_volume)  # Convert the input volume to a float
    if input_volume > 1:  # If the volume is greater than 1, set it to 1
        input_volume = 1
    elif input_volume < 0:  # If the volume is less than 0, set it to 0
        input_volume = 0
    pygame.mixer.music.set_volume(input_volume)  # Set the volume

# Define a function to set the minimum time between plays
def set_min_time_between(input_time):
    global min_time_bewteen_play  # Use the global variable
    min_time_bewteen_play = input_time  # Set the minimum time between plays