Generate Unique Music from Your Ideas with Musicgen

25 Apr 2025
Generate Unique Music from Your Ideas with Musicgen

Musicgen is a powerful API designed to transform your creative prompts into beautiful music compositions. By leveraging advanced AI models, Musicgen allows developers to generate music based on textual descriptions or existing audio inputs. This service simplifies the music creation process, enabling users to produce unique soundscapes quickly and efficiently, without the need for extensive musical knowledge or skills.

Imagine being able to create a cinematic score for your film project or generate a catchy tune for your video game just by describing it in words. Musicgen excels in various scenarios, such as enhancing multimedia projects, creating personalized soundtracks, or exploring musical concepts. With its flexibility and ease of use, Musicgen is an essential tool for developers looking to integrate music generation into their applications.

Prerequisites

To get started with Musicgen, you'll need a Cognitive Actions API key and a basic understanding of making API calls.

Generate Music From Prompt

The "Generate Music From Prompt" action is the core feature of Musicgen, enabling users to create music based on specified prompts or melodies. This action supports various input types and offers options to control the generated music's characteristics, making it a versatile tool for developers.

Purpose

This action allows you to create music that aligns with your creative vision, whether you're looking for a specific mood, genre, or progression. It addresses the challenge of music composition by providing an automated solution that can generate high-quality audio based on user-defined parameters.

Input Requirements

The input for this action is structured as a JSON object and includes various parameters such as:

  • prompt: A string describing the desired music (e.g., "Edo25 major g melodies that sound triumphant and cinematic").
  • duration: An integer specifying the audio length in seconds.
  • inputAudio: A URI for an audio file, if you want to influence the generated music with an existing melody.
  • modelVersion: A string to select the model used for generation (e.g., "stereo-large").
  • outputFormat: The format of the generated audio file, such as "wav" or "mp3".

Expected Output

The output will be a link to the generated audio file, which you can download and use in your projects. For instance, a typical response might look like: https://assets.cognitiveactions.com/invocations/.../ad9beb4a-d0bb-42fc-b899-002bb013d99f.mp3.

Use Cases for this Action

  • Film Scoring: Quickly generate background scores to match specific scenes or emotions.
  • Game Development: Create immersive soundtracks that adapt to gameplay.
  • Music Exploration: Experiment with different musical ideas and concepts without needing to compose manually.
  • Personalized Music: Generate unique tracks for events, such as weddings or birthdays, tailored to specific themes or preferences.
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "6f90dbbb-f7b0-489c-a113-bd396116e3c9" # Action ID for: Generate Music From Prompt

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "topK": 250,
  "topP": 0,
  "prompt": "Edo25 major g melodies that sound triumphant and cinematic. Leading up to a crescendo that resolves in a 9th harmonic",
  "duration": 8,
  "temperature": 1,
  "continuation": false,
  "modelVersion": "stereo-large",
  "outputFormat": "mp3",
  "continuationStart": 0,
  "multiBandDiffusion": false,
  "normalizationStrategy": "peak",
  "classifierFreeGuidance": 3
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")

Conclusion

Musicgen empowers developers to generate custom music effortlessly, saving time and resources while enhancing creative projects. With its robust features and flexible input options, you can easily integrate music generation into your applications. Whether you're building a game, producing a film, or simply exploring musical ideas, Musicgen offers the tools you need to bring your audio visions to life. Start experimenting today and unlock the potential of automated music creation!