How to setup physical switches to control playback in MoodeAudio

 Hello there. Its been a long time . 

Recently i was trying out to build a DAC with Raspberry PI and IQAudio DAC. My choice of hardware is very cheap and it's a very small setup. Following is my Hardware

Raspberry PI 3 A+

IQAudio DAC+

For operating system I chose MoodeAudio over Volumio since its a open source alternative. And it had it's issues . But i don't want to pay for my OS. So I went for MoodeAudio.

Initial setup was very easy. Everything went so good i was able to play my song. The issue is there is no display. I tried to install a 3.5" touch display which is connected via GPIO. It was unsuccessfully. So i decided to have some physical switches to control playback. My controls were limited. Play/Pause, Next/previous, volume +/- and mute. 

I tried with encoder for volume but its not working correctly. It adjusts volume but it's not working as expected. So i switch to physical press buttons. I bought some cheap momentary switches to test. I used a python script to listen GPIO. Here is the code i used 

#!/usr/bin/python3

import lgpio
import time
import requests

# MoodeAudio API URL
MOODE_URL = "http://moode.local/command/?cmd="  # Replace <moode_ip> with your MoodeAudio IP address


# Define pin numbers for buttons
pins = {
    4: "volume_up",
    5: "volume_down",
    6: "mute",
    17: "next",
    27: "previous",
    22: "play_pause"  # New pin for play/pause
}  # Example pins, adjust as needed

h = lgpio.gpiochip_open(0)

# Claim the pins and set pull-ups
for pin in pins.keys():
    lgpio.gpio_claim_input(h, pin, lgpio.SET_PULL_UP)

# Current volume state
current_volume = 50  # Default volume (set to your preferred starting point)

def get_current_volume():
    """Fetch current volume from MoodeAudio"""
    try:
           response = requests.get(f"{MOODE_URL}get_volume")
        if response.status_code == 200:
            data = response.json()
            volume = int(data.get("volume", 50))  # Default to 50 if missing
            print(f"Current volume from MoodeAudio: {volume}")
            return volume
        else:
            print("Failed to fetch volume")
    except Exception as e:
        print(f"Error fetching volume: {e}")
    return 50  # Fallback value



def set_volume(volume):
    """Sets the volume via MoodeAudio API"""
    try:
        response = requests.get(f"{MOODE_URL}set_volume {volume}")
        if response.status_code == 200:
            print(f"Volume set to {volume}")
        else:
            print("Failed to set volume")
    except Exception as e:
        print(f"Error setting volume: {e}")

def mute():
    """Toggles mute via MoodeAudio API"""
    try:
        response = requests.get(f"{MOODE_URL}set_volume mute")
        if response.status_code == 200:
            print("Mute toggled")
        else:
            print("Failed to toggle mute")
    except Exception as e:
        print(f"Error toggling mute: {e}")

def next_track():
    """Go to the next track (for example, call the next API)"""
    try:
        response = requests.get(f"{MOODE_URL}next")
        if response.status_code == 200:
            print("Next track")
        else:
            print("Failed to go to next track")
    except Exception as e:
        print(f"Error skipping to next track: {e}")

def previous_track():
    """Go to the previous track (for example, call the previous API)"""
    try:
        response = requests.get(f"{MOODE_URL}previous")
        if response.status_code == 200:
            print("Previous track")
        else:
            print("Failed to go to previous track")
    except Exception as e:
        print(f"Error skipping to previous track: {e}")

def play_pause():
    """Toggle play/pause via MoodeAudio API"""
    try:
        response = requests.get(f"{MOODE_URL}pause")
        if response.status_code == 200:
            print("Toggled play/pause")
        else:
            print("Failed to toggle play/pause")
    except Exception as e:
        print(f"Error toggling play/pause: {e}")

try:
    while True:
        for pin, action in pins.items():
            state = lgpio.gpio_read(h, pin)
            if state == 0:  # Button is pressed (active low)
                if action == "volume_up":
                    current_volume = min(current_volume + 5, 100)  # Increase volume, max 100
                    set_volume(current_volume)
                elif action == "volume_down":
                    current_volume = max(current_volume - 5, 0)  # Decrease volume, min 0
                    set_volume(current_volume)
                elif action == "mute":
                    mute()  # Toggle mute
                elif action == "next":
                    next_track()  # Next track
                elif action == "previous":
                    previous_track()  # Previous track
                elif action == "play_pause":
                    play_pause()  # Toggle play/pause
                time.sleep(0.5)  # Debounce time for button press
        time.sleep(0.2)
except KeyboardInterrupt:
    lgpio.gpiochip_close(h)

So the code is loaded using rc.local. To run the script every boot follow he steps

Edit the file 
sudo nano /etc/rc.local

Add this before the exit 0 line:

/usr/bin/python3 /usr/local/bin/switch.py &

Make sure the file is executable:

sudo chmod +x /usr/local/bin/switch.py
Lets restart the system.

Switch connection


Comments

MARKETING said…
Great guide! Setting up physical switches for playback control in MoodeAudio makes the listening experience much more tactile and convenient.

<a href="https://digitalfloats.com/graphic-design-course-in-
hyderabad/">new How to setup physical switches to control playback in MoodeAudio;/a>

https://digitalfloats.com/graphic-design-course-in-hyderabad/






Popular posts from this blog

Configure PostgreSQL and phpPgAdmin in WAMP

Angular - 4 year road map

Flash FLV player using PHP