Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
You can generate background music from JSON in .NET by sending a JSON request to the ElevenLabs Music API at POST https://api.elevenlabs.io/v1/music. The JSON describes the track, either as a short text prompt or as a structured composition_plan, and the response body is generated audio that you write to a file. The vendor’s documentation shows Python and TypeScript examples, not C#, so the .NET side is a plain HttpClient call with System.Text.Json serialization. No official .NET SDK method is involved.
JSON is the control format here, not the output format. You never receive a JSON music file back. Also note that speech-focused audio APIs with C# examples, such as OpenAI’s Audio API, generate speech or transcription, not music, so they do not solve this task.
Before you write code
- Paid access is required. The ElevenLabs Music quickstart states: “The Music API is only available to paid users.” A free account will not complete the request.
- Create an API key in your ElevenLabs account and store it outside your source code, in an environment variable such as
ELEVENLABS_API_KEYor a secret manager. The key travels in thexi-api-keyrequest header. - Check the current reference. Request fields, model IDs and paid-plan rules are volatile. The details below reflect the vendor documentation as of October 2026; confirm them against the live Music API reference before you ship anything.
Choose between a prompt and a composition plan
Every request uses exactly one of two inputs. Sending prompt and composition_plan together is rejected by design.
| Factor | Text prompt | Composition plan |
|---|---|---|
| Best for | Quick prototypes from a plain-language description | Controlled section order, lyric timing and arrangement |
| Input shape | prompt string |
composition_plan object with an ordered chunks array |
| Length control | music_length_ms, documented range 3,000 to 600,000 ms |
Per-section duration_ms values; confirm total-length validation in the current guide |
| Instrumental switch | force_instrumental: true guarantees an instrumental result |
Not available; the field is accepted only with a prompt |
| Models in the reference | music_v1, music_v2, music_v2_5 |
Chunk-based plans are documented for music_v2 and music_v2_5 |
How a composition plan is structured
The composition-plan guide describes an ordered array of chunks. Each chunk is one section of the track, and it carries these fields:
#1 Best Overall
- Next-Gen Music Production and Beat Maker Essential - USB-powered MIDI keyboard controller with 25 mini velocity-sensitive keys, optimized for studio or beat production, piano-style performance, synth leads, sample triggering
- Real-Time Control and Navigation - 8x assignable 360° knobs, a vibrant full-color screen and push/turn encoder for hands-on access to settings, presets, and DAW functions, without reaching for a computer
- Iconic MPC Pads with RGB Feedback - 8 velocity- and pressure-sensitive MPC pads deliver an iconic finger-drumming experience, plus dynamic visual feedback to match your performance in studio or on the go
- Studio Instrument Collection Included - A powerful VST/AU and standalone virtual suite packing 1000+ pro-grade drums, keys, synths, bass, FX from AIR, Akai Pro and Moog, plus MPK Mini IV integrated controls
- Pre-Mapped DAW Integration - Get producing in under 15 minutes with Ableton Live Lite 12, Logic Pro, FL Studio and more; comes with an expanded DAW-mapped transport section for uninterrupted workflow
- text: a section label and optional directions, such as
[Intro]. Lyrics can appear here and may be in a language other than English. - duration_ms: the length of that section in milliseconds.
- positive_styles: style descriptors to include. The guide asks for these in English.
- negative_styles: styles to avoid, such as
vocalsfor a background bed. - context_adherence: how closely the section should follow its styles and directions.
According to the guide’s explanation, the first chunk’s styles set the overall tone of the track, so put your most important mood descriptors there. The following JSON is an illustrative shape that uses the documented field names. It is not vendor-tested output, and the exact sound you get will vary.
{
"model_id": "music_v2_5",
"composition_plan": {
"chunks": [
{
"text": "[Intro]",
"duration_ms": 12000,
"positive_styles": ["ambient", "warm piano", "soft strings"],
"negative_styles": ["vocals", "lyrics", "percussion"],
"context_adherence": "high"
},
{
"text": "[Main Theme]",
"duration_ms": 48000,
"positive_styles": ["calm", "cinematic", "gentle movement"],
"negative_styles": ["vocals", "lyrics", "abrupt changes"],
"context_adherence": "high"
}
]
}
}
Generate and save the track in C#
Set up the project and key
- Export the key. On Linux or macOS, run
export ELEVENLABS_API_KEY="your-key". In PowerShell, run$env:ELEVENLABS_API_KEY = "your-key". - Create a console project with
dotnet new console -n BackgroundMusic, then runcd BackgroundMusic. - Replace the contents of
Program.cswith the prompt-based program below. - Run
dotnet run. A file namedbackground.mp3should appear in the output directory.
Prompt-based request
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("ELEVENLABS_API_KEY")
?? throw new InvalidOperationException("Set ELEVENLABS_API_KEY first.");
var request = new
{
prompt = "Calm cinematic background music, warm piano, soft strings, no vocals",
music_length_ms = 30000,
model_id = "music_v2_5",
force_instrumental = true
};
var json = JsonSerializer.Serialize(request);
using var http = new HttpClient();
using var message = new HttpRequestMessage(HttpMethod.Post, "https://api.elevenlabs.io/v1/music")
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
message.Headers.Add("xi-api-key", apiKey);
using var response = await http.SendAsync(message);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new HttpRequestException($"Music request failed: {(int)response.StatusCode} {error}");
}
var audio = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync("background.mp3", audio);
Console.WriteLine($"Saved {audio.Length} bytes to background.mp3");
The status check runs before the file is written, so a rejected request never leaves a corrupt file behind. The example assumes an MP3 output. If you request a different output format, change the extension to match, and check the response Content-Type header to confirm what came back.
Rank #2
- Full Creative Control - A dynamic 37-Key MPK Mini keybed for 3 full octaves of melodic and harmonic performance; Easily connect to your DAW or studio equipment with the USB-powered MIDI Controller
- Advanced Connectivity - Connect to different sound sources with CV/Gate and MIDI I/O; Control modular gear, sound modules, synthesizers, and more to bring new sound sources into your music production
- Native Kontrol Standard (NKS) Integration - Akai Professional and Native Instruments have partnered to bring NKS support to the MPK Controller series, get ready to Kontrol straight from your MPK
- Choose Your Exclusive Complimentary NKS Bundle - Browse and control Native Instruments presets and sound libraries; select one of three curated Komplete 15 Select bundles: Beats, Band, or Electronic
- Record and Compose Without a Computer - Connect to your production station and use the built-in 64-step sequencer featuring one track for drums and one for melodies or chords, with up to 8 notes each
Plan-based request
For a composition plan, replace the request object with the object below. Everything from JsonSerializer.Serialize onward stays the same. The object contains no prompt field, and the chunk durations determine the arrangement.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Best Value
- The Creative Controller: Launchkey is an all-in-one DAW controller with premium keybeds and 16 responsive FSR pads for drumming, clip launching, and more
- Seamless DAW Integration: Launchkey works with all major DAWs, offering intuitive workflows for Ableton Live, Logic, Cubase, Reason, Reaper, FL Studio, and Ardour
- Go Beyond Finger Drumming: Launchkey’s FSR drum pads with polyphonic aftertouch also serve as step sequencers, clip launchers, chord triggers, and more
- Everything in the box: Ableton Live Lite, Cubase LE, Novation Play, sounds from GForce, Klevgrand, Orchestral Tools, Native Instruments, and free Melodics lessons
- Powerful Creative Tools: Never hit a wrong note with Scale Mode, trigger lush chords from a single key or drum pad, and create and mutate wild arpeggios
Rank #4
- Compact yet powerful standalone mini keyboard with built-in speaker and USB MIDI Controller capabilities for beat makers, songwriters and musicians
- 25-Key Gen 2 MPK Mini dynamic keybed, OLED Display, 8 Velocity sensitive backlit MPC drum pads, arpeggiator and note repeat, plus 4 encoder knobs deliver a professional, versatile performance
- Native Kontrol Standard (NKS) Integration - Akai Professional and Native Instruments have partnered to bring NKS support to the MPK Controller series, get ready to Kontrol straight from your MPK
- Choose Your Exclusive Complimentary NKS Bundle - Browse and control Native Instruments presets and sound libraries; select one of three curated Komplete 15 Select bundles: Beats, Band, or Electronic
- Over 100 internal drum and instrument sounds including acoustic and electric pianos, synth leads, pads and more
Rank #3
- Music Production and Beat Maker Essential -USB powered MIDI controller with 25 mini MIDI keyboard velocity-sensitive keys for studio production, virtual synthesizer control and beat production
- Total Control of your Production - Innovative 4-way thumbstick for dynamic pitch and modulation control, plus a built-in arpeggiator with adjustable resolution, range and modes
- Native Kontrol Standard (NKS) Integration - Akai Professional and Native Instruments have partnered to bring NKS support to the MPK Controller series, get ready to Kontrol straight from your MPK
- Choose Your Exclusive Complimentary NKS Bundle - Browse and control Native Instruments presets and sound libraries; select one of three curated Komplete 15 Select bundles: Beats, Band, or Electronic
- The MPC Experience - 8 backlit velocity-sensitive MPC-style MIDI beat pads with Note Repeat and Full Level for programming drums, triggering samples and controlling virtual synthesizer / DAW controls
var request = new
{
model_id = "music_v2_5",
composition_plan = new
{
chunks = new[]
{
new { text = "[Intro]", duration_ms = 12000, positive_styles = new[] { "ambient", "warm piano" }, negative_styles = new[] { "vocals" }, context_adherence = "high" },
new { text = "[Main Theme]", duration_ms = 48000, positive_styles = new[] { "calm", "cinematic" }, negative_styles = new[] { "vocals", "abrupt changes" }, context_adherence = "high" }
}
}
};
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting and limits
- Both inputs sent: a request containing
promptandcomposition_planis invalid. Remove one. - Instrumental flag with a plan:
force_instrumentalworks only with a prompt. For a plan, control vocals throughnegative_stylesinstead. - Prompt length out of range:
music_length_msmust be between 3,000 and 600,000 milliseconds. - Plan on an unsupported model: chunk-based plans are documented for
music_v2andmusic_v2_5. - Non-success status: the code above throws and writes nothing. Read the error body first, then fix the request. A 401-style rejection usually points to a missing or wrong key, or to an account without paid access.
- Repeat requests differ: the reference says a seed can improve consistency, but exact reproducibility is not guaranteed, and output can change when the service is updated. Store the generated files if you need a specific track again.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

