Building an Unofficial Google Music FX API Client in Python

Building an Unofficial Google Music FX API Client in Python

Hey fellow developers! :wave:

I’m excited to share a project I’ve been working on recently — an unofficial Python client for Google’s Music FX API. This tool allows you to generate AI-powered music from text prompts, even in regions where the service isn’t officially available.

The Problem

Google’s Music FX is an amazing tool that can generate custom music based on text descriptions. Unfortunately, it’s not available in many countries including India. As developers, geographical restrictions shouldn’t limit our ability to explore and build with interesting technologies!

The Solution

I’ve built a Python client that interacts with Google’s Music FX API endpoints. The client handles:

  • Authentication with the API
  • Sending text prompts for music generation
  • Processing and saving the resulting audio files

How It Works

The core of the application is the APIClient class which handles the API communication:

def generate_music(self, music_prompt, generation_count=2, loop=False, sound_length_seconds=70, model="DEFAULT"):
    """Generate music based on a text prompt."""
    headers = {
        "Authorization": f"Bearer {self.auth_token}",
        "Content-Type": "application/json;charset=UTF-8",
        "Accept": "*/*"
    }
    
    payload = {
        "generationCount": generation_count,
        "input": {"textInput": music_prompt},
        "loop": loop,
        "soundLengthSeconds": sound_length_seconds,
        "model": model,
        "clientContext": {
            "tool": "MUSICLM_V2",
            "sessionId": self.session_id
        }
    }
    
    response = requests.post(self.url, headers=headers, json=payload)
    # Process response...

Technical Challenges

Authentication

Music FX requires valid authorization tokens. To address this, I implemented a configuration system that securely stores and manages the tokens:

class Settings:
    AUTH_TOKEN = os.getenv("AUTH_TOKEN")
    SESSION_ID = os.getenv("SESSION_ID")
    
    MAX_GENERATION_COUNT = int(os.getenv("MAX_GENERATION_COUNT", 3))
    ALLOWED_SOUND_LENGTHS = [int(x) for x in os.getenv("ALLOWED_SOUND_LENGTHS", "30,50,70").split(",")]

Rate Limiting and API Constraints

The API has limitations:

  • Maximum of 3 generations per request
  • Sound lengths limited to 30, 50, or 70 seconds

I built validation to respect these limits:

if generation_count > Settings.MAX_GENERATION_COUNT:
    raise ValueError(f"generation_count cannot exceed {Settings.MAX_GENERATION_COUNT}.")
if sound_length_seconds not in Settings.ALLOWED_SOUND_LENGTHS:
    raise ValueError(f"sound_length_seconds must be one of {Settings.ALLOWED_SOUND_LENGTHS}.")

Implementation Details

Project Structure

Google-Music-FX-unofficial-/
├── src/
│   ├── config/
│   │   └── settings.py
│   ├── models/
│   │   └── audio_model.py
│   ├── services/
│   │   └── api_client.py
│   └── utils/
│       ├── file_utils.py
│       └── validation_utils.py
├── tests/
├── main.py
├── requirements.txt
└── README.md

Environmental Configuration

I’ve used Python’s dotenv for configuration, allowing users to customize parameters without changing code:

AUTH_TOKEN="your-auth-token"
SESSION_ID="your-session-id"
MAX_GENERATION_COUNT=3
ALLOWED_SOUND_LENGTHS="30,50,70"

How to Get Started

If you want to try it out:

  1. Clone the repository:
git clone https://github.com/debasishtripathy13/Google-Music-FX-unofficial-.git
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up your .env file with your credentials.
  2. Run and generate music:
python main.py

Future Plans

I’m working on extending the client with:

  1. A web interface for easier interaction
  2. Support for additional API parameters
  3. Integration with music production tools

Looking for Contributors!

If you’re interested in:

  • Extending functionality
  • Improving the authentication mechanism
  • Adding a GUI
  • Writing better documentation

Please check out the repository and consider contributing!

Questions?

Have you worked with similar API projects? What challenges did you face with region-locked APIs? I’d love to hear your thoughts and experiences in the comments!


GitHub Repository

ai python #MusicGeneration #APIClient #OpenSource

1 Like