Freenove / Freenove_Big_Hexapod_Robot_Kit_for_Raspberry_Pi

Apply to FNK0052
Other
114 stars 86 forks source link

Playing audio #32

Closed drperpen closed 6 months ago

drperpen commented 6 months ago

Hi, I finished building the Hexapod with no issues, and I have my client on my Ubuntu 20.04 machine. Everything worked fine, including all modules.

Then I modified the code to add a "Hello" button that plays a .wav audio file stored on the Raspberry. The button logic is working fine and transmitting the command properly to the server. However it looks that when starting the server (main.py) on the Raspberry it takes over the audio module and I get this error:

  File "/home/pi/Freenove_Big_Hexapod_Robot_Kit_for_Raspberry_Pi/Code/Server/Server.py", line 127, in play_audio
    pygame.mixer.init()
pygame.error: ALSA: Couldn't open audio device: Unknown error 524

I have tried play the same file from a test script on the raspberry, and it works fine with no errors:

import pygame

#Audio
def play_audio():
    pygame.mixer.init()
    pygame.mixer.music.load('/home/pi/audio/hello.wav')
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy(): 
        pygame.time.Clock().tick(10)

print("Playing audio...")
play_audio()

Is there a way for the server process to release the audio module, or maybe another way I can access the audio? Thanks!

Shaynee-MO commented 6 months ago

Hi! Sorry but we do not have instructions for this.

drperpen commented 6 months ago

@Shaynee-MO , it was a problem with two issues combined. One, the Led module is somehow corrupting the audio module and two, the fact that the server script is running on sudo and Pulseaudio doesn't like that. I was able to play audio while connected client>server with this workaround:

  1. Comment the line self.led=Led() on Server.py (of course on the raspberry side, and you will loose the Led feature)
  2. To play sounds I created this function:

    def play_audio(self):
        """ Play an audio file using aplay """
        try:
            # Attempt to play the sound
            print("Trying to play the sound...")
    
            # By using '--device=hw:2,0' we are bypassing Pulseaudio
            subprocess.Popen(['aplay', '--device=hw:2,0' , '/home/pi/audio/hello.wav'])
        except subprocess.CalledProcessError as e:
            print(f"Error playing audio: {e}")

    And then adding this in the same Server.py:

            for oneCmd in cmdArray:
                data=oneCmd.split("#")
                if data==None or data[0]=='':
                    continue
    
                #Audio
                elif cmd.CMD_AUDIO in data:
                    print(data)
                    self.play_audio()
                    ### ... the rest of the code

    You will need to add CMD_AUDIO = "CMD_AUDIO" on both server (raspberry) and client (local machine) Command.py

    I might inspect further what part of the Led module is causing the problem with the raspberry audio.