Add music recognition to a Unity game
Record a few seconds from the microphone in Unity, encode it as WAV, upload it with UnityWebRequest to your own server, and read the song AudD found; with a C# server on the AudD .NET SDK, microphone permissions on Android and iOS, the no-match case and errors.
You can identify the song that’s playing near the player in a Unity game. When the player presses a button, the game records 10 seconds from the microphone with the Microphone class and sends the recording to your server as a WAV file. Your server sends the recording to AudD’s Music Recognition API with your token. AudD’s response will contain the title and artist of the song, and a link to the song’s lis.tn page, and the game shows them. It’s for rhythm games, music apps and streamer tools made in Unity. The scripts use the Unity 6.6 scripting reference, the current version in November 2026, and the APIs they call are in Unity 6.3 LTS too.
Don’t put your API token in the game. You can share the results with your players, but please don’t include your API tokens in the client-side software. If you put your token in a game, anyone who has a copy of the game can use the token to access the AudD API with your account. See Keeping your API token on the server.
How it works
The game records 10 seconds of audio with Microphone.Start, encodes the samples as a 16-bit WAV file, and posts the file to your server’s /identify route in the file parameter, using multipart/form-data in the usual way browsers upload files. Your server calls AudD with the token and sends back only the fields the game shows. If there are no matches, the game asks the player to try again.
Our .NET SDK is for the server. It targets .NET 6 and .NET 8, while Unity supports two API compatibility levels, .NET Standard 2.1 and .NET Framework 4.8. So the game sends the clip with UnityWebRequest, and the SDK calls AudD on your server.
The server
The server is a small ASP.NET Core app on our .NET SDK. You need the .NET 8 SDK or later, and an API token: you can get a token from our API Dashboard. For a first try, the public test token allows 10 requests a day. Create the project and add the SDK:
dotnet new web -n SongIdServer
cd SongIdServer
dotnet add package AudD
Replace the contents of the file Program.cs with the following:
// Program.cs: the only place your AudD token exists.
using System.Threading.RateLimiting;
using AudD;
using AudD.DependencyInjection;
using Microsoft.AspNetCore.Http.Features;
const long MaxUpload = 10 * 1024 * 1024; // 10 MB, the standard endpoint's limit
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAudD(); // reads AUDD_API_TOKEN from the environment
builder.Services.Configure<FormOptions>(o => o.MultipartBodyLengthLimit = MaxUpload);
// A per-IP limit: 20 recognitions per hour.
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
o.OnRejected = (context, token) => new ValueTask(
context.HttpContext.Response.WriteAsJsonAsync(new { error = "too_many_requests" }, token));
o.AddPolicy("per-ip", http => RateLimitPartition.GetFixedWindowLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromHours(1) }));
});
var app = builder.Build();
_ = app.Services.GetRequiredService<AudD.AudD>(); // fails here, at startup, without a token
app.UseRateLimiter();
app.MapPost("/identify", async (HttpRequest request, AudD.AudD audd, ILogger<Program> logger) =>
{
if (!request.HasFormContentType)
return Results.Json(new { error = "send_a_file" }, statusCode: 400);
IFormFile? file;
try
{
file = (await request.ReadFormAsync()).Files.GetFile("file");
}
catch (InvalidDataException) // the upload is over MaxUpload
{
return Results.Json(new { error = "LIMIT_FILE_SIZE" }, statusCode: 413);
}
if (file is null)
return Results.Json(new { error = "send_a_file" }, statusCode: 400);
using var buffer = new MemoryStream();
await file.CopyToAsync(buffer);
try
{
var song = await audd.RecognizeAsync(buffer.ToArray());
if (song is null)
return Results.Json(new { match = false });
// Only the fields the game shows.
return Results.Json(new
{
match = true,
artist = song.Artist,
title = song.Title,
album = song.Album,
songLink = song.SongLink,
});
}
catch (AudDInvalidAudioException)
{
return Results.Json(new { error = "unreadable_audio" }, statusCode: 422);
}
catch (AudDException e)
{
logger.LogError(e, "Recognition failed"); // the details stay in your logs
return Results.Json(new { error = "recognition_failed" }, statusCode: 502);
}
}).RequireRateLimiting("per-ip");
app.Run();
Run it with your token:
AUDD_API_TOKEN=your-api-token dotnet run --urls http://localhost:3000
In another terminal, download our example file and send it to the server:
curl -o example.mp3 https://audd.tech/example.mp3
curl -F [email protected] http://localhost:3000/identify
{"match":true,"artist":"Tears For Fears","title":"Everybody Wants To Rule The World","album":"Songs From The Big Chair","songLink":"https://lis.tn/NbkVb"}
The server checks the request, calls AudD with the token, and sends back only these four fields. If there are no matches, it answers {"match": false}. If the file is bigger than 10 MB, the server responds with 413, and if the audio can’t be read, with 422. For any other error, it responds with 502 and logs the details. The server limits how often a player can call it: an IP address over 20 requests an hour gets 429. If the server runs behind a reverse proxy or a load balancer, every player will share one limit, so count requests per signed-in player instead.
The token comes from the AUDD_API_TOKEN environment variable, and the server stops at startup if it isn’t set. The Node server in Keeping your API token on the server takes the same file field and gives the same answers, so the game works with either one.
Record the clip and encode it as WAV
Create a script named WavEncoder.cs with the following content. The game uses it to turn the samples of the recording into a WAV file that it can upload.
using System;
using System.IO;
using System.Text;
public static class WavEncoder
{
// Encodes samples from AudioClip.GetData (floats from -1 to 1,
// interleaved by channel) as a 16-bit PCM WAV file.
public static byte[] Encode(float[] samples, int channels, int frequency)
{
int dataBytes = samples.Length * 2;
using var stream = new MemoryStream(44 + dataBytes);
using var writer = new BinaryWriter(stream); // always little-endian
writer.Write(Encoding.ASCII.GetBytes("RIFF"));
writer.Write(36 + dataBytes);
writer.Write(Encoding.ASCII.GetBytes("WAVE"));
writer.Write(Encoding.ASCII.GetBytes("fmt "));
writer.Write(16); // size of this chunk
writer.Write((short)1); // format: PCM
writer.Write((short)channels);
writer.Write(frequency); // samples per second
writer.Write(frequency * channels * 2); // bytes per second
writer.Write((short)(channels * 2)); // bytes per frame
writer.Write((short)16); // bits per sample
writer.Write(Encoding.ASCII.GetBytes("data"));
writer.Write(dataBytes);
foreach (float sample in samples)
writer.Write((short)(Math.Clamp(sample, -1f, 1f) * short.MaxValue));
writer.Flush();
return stream.ToArray();
}
}
The standard endpoint analyzes up to the first 12 seconds of audio, so the game records 10 seconds. A 16-bit mono WAV file of 10 seconds takes 882,044 bytes at 44,100 Hz and 960,044 bytes at 48,000 Hz: it usually takes less than one megabyte, and the standard endpoint accepts files up to 10 MB.
Send it to your server and show the song
Create a script named SongIdentifier.cs with the following content. Then change identifyUrl to the address of your server, in the script or in the Inspector.
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
#if UNITY_ANDROID && !UNITY_EDITOR
using UnityEngine.Android;
#endif
public class SongIdentifier : MonoBehaviour
{
// Your server's address. The AudD token lives there, not in the game.
[SerializeField] string identifyUrl = "https://your-server.example/identify";
[SerializeField] int clipSeconds = 10;
string status = "Play some music and press Identify.";
string songLink;
bool busy;
void OnGUI()
{
GUILayout.BeginArea(new Rect(20, 20, 400, 200));
GUILayout.Label(status);
GUI.enabled = !busy;
if (GUILayout.Button("Identify"))
StartCoroutine(Identify());
GUI.enabled = true;
if (songLink != null && GUILayout.Button("Open the song"))
Application.OpenURL(songLink);
GUILayout.EndArea();
}
IEnumerator Identify()
{
busy = true;
songLink = null;
try
{
// 1. Ask for the microphone.
#if UNITY_ANDROID && !UNITY_EDITOR
if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
{
bool answered = false;
var callbacks = new PermissionCallbacks();
callbacks.PermissionGranted += _ => answered = true;
callbacks.PermissionDenied += _ => answered = true;
callbacks.PermissionRequestDismissed += _ => answered = true;
Permission.RequestUserPermission(Permission.Microphone, callbacks);
yield return new WaitUntil(() => answered);
}
bool allowed = Permission.HasUserAuthorizedPermission(Permission.Microphone);
#elif (UNITY_IOS || UNITY_WEBGL) && !UNITY_EDITOR
yield return Application.RequestUserAuthorization(UserAuthorization.Microphone);
bool allowed = Application.HasUserAuthorization(UserAuthorization.Microphone);
#else
bool allowed = true;
#endif
if (!allowed)
{
status = "Allow microphone access in Settings to identify songs.";
yield break;
}
if (Microphone.devices.Length == 0)
{
status = "No microphone found.";
yield break;
}
// 2. Record clipSeconds of audio from the default microphone.
int frequency = AudioSettings.outputSampleRate;
Microphone.GetDeviceCaps(null, out int minFreq, out int maxFreq);
if (maxFreq > 0)
frequency = Mathf.Clamp(frequency, minFreq, maxFreq);
AudioClip clip = Microphone.Start(null, false, clipSeconds, frequency);
if (clip == null)
{
status = "Couldn't start the microphone.";
yield break;
}
status = "Listening...";
float deadline = Time.realtimeSinceStartup + clipSeconds + 2;
while (Microphone.IsRecording(null) && Time.realtimeSinceStartup < deadline)
yield return null;
Microphone.End(null);
var samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
byte[] wav = WavEncoder.Encode(samples, clip.channels, clip.frequency);
Destroy(clip);
// 3. Upload the WAV to your server as the "file" field.
status = "Looking it up...";
var form = new WWWForm();
form.AddBinaryData("file", wav, "clip.wav", "audio/wav");
using UnityWebRequest request = UnityWebRequest.Post(identifyUrl, form);
request.timeout = 30;
yield return request.SendWebRequest();
// 4. Read the answer.
if (request.result == UnityWebRequest.Result.ConnectionError)
{
status = "Couldn't reach the server. Check your connection and try again.";
yield break;
}
if (request.responseCode != 200)
{
status = request.responseCode switch
{
422 => "Couldn't read that recording. Try again.",
429 => "Too many tries. Wait a while and try again.",
_ => $"Something went wrong ({request.responseCode}). Try again later.",
};
yield break;
}
IdentifyResponse answer = null;
try
{
answer = JsonUtility.FromJson<IdentifyResponse>(request.downloadHandler.text);
}
catch (Exception)
{
// Not the JSON your server sends.
}
if (answer == null)
status = "Something went wrong. Try again later.";
else if (!answer.match)
status = "No match. Move closer to the music and try again.";
else
{
status = $"{answer.title}\n{answer.artist}";
if (!string.IsNullOrEmpty(answer.songLink) && answer.songLink.StartsWith("https://", StringComparison.Ordinal))
songLink = answer.songLink;
}
}
finally
{
busy = false;
}
}
[Serializable]
public class IdentifyResponse
{
public bool match;
public string artist;
public string title;
public string album;
public string songLink;
}
}
Add the script to a GameObject in your scene and press Play. Play a song near the microphone, then press Identify in the top-left corner of the Game view. While the game is listening, the button is disabled. After about 10 seconds, you should see the title and artist of the song. Press Open the song to open the song’s lis.tn page, which links to the streaming platforms.
The script records from the default microphone at the project’s output sample rate, AudioSettings.outputSampleRate, or the closest rate the device reports. The clip doesn’t loop, so the recording stops by itself after 10 seconds. The WAV file is sent with UnityWebRequest.Post and a WWWForm, as multipart/form-data. If the server doesn’t answer within 30 seconds, the request times out. The buttons are drawn with OnGUI so that the script works in any project; replace them with your own UI.
Try it in the Editor
The server from this page listens on http://localhost:3000, so set identifyUrl to http://localhost:3000/identify while you test in the Editor. Unity doesn’t allow plain HTTP by default: the Allow downloads over HTTP Player setting is Not Allowed. While you test against your computer, set it to Always Allowed, and set it back to Not Allowed when your server has an HTTPS address. A build on a phone can’t reach localhost, so put the server online before you test on a device. Start the server with the test token if you don’t have your own token yet, but keep in mind that it allows 10 requests a day. For more on testing without spending requests, see Testing your integration.
When result is null
If the server has successfully processed the request, but there are no matches, the result field is null. Your server then answers {"match": false}, and the game shows “No match”. It’s not an error, so there’s nothing to retry automatically: let the player press Identify again. If the music was quiet, or the recording was mostly talking or game sounds, ask the player to move closer to the speaker.
When something goes wrong
When the player is offline
If the device is offline or the game can’t connect to your server, request.result is ConnectionError, and the game asks the player to check the connection and try again. If your server doesn’t answer within 30 seconds, the request times out and the game asks the player to try again too. We don’t recommend retrying automatically: a cancelled request might still consume requests.
When the microphone isn’t allowed
If the player denies the permission, the game asks them to allow it in Settings. If the recording can’t start, Microphone.Start returns null, and the game shows that it couldn’t start the microphone. If Microphone.devices is empty, there’s no microphone to record from, and the game says so.
When your server returns an error
Your server responds with 422 if the audio couldn’t be read, and with 429 if more than 20 clips came from one IP address within an hour. For any other error, it responds with 502, and the details stay in your server’s log. The Error codes page explains what our errors mean.
Platform notes
Android
If the application uses the Microphone class, Unity adds the RECORD_AUDIO permission to the Android App Manifest. The script checks whether the player has already granted the permission. If not, it requests it with Permission.RequestUserPermission and waits for the answer before it records. It’s best practice to show the player a message that explains why the game needs the microphone before you send the request. The internet permission comes from the Internet Access Player setting: on Auto, Unity adds it if you are using a networking API.
iOS and macOS
Enter the reason for accessing the microphone in Microphone Usage Description, in the Player settings for iOS. iOS shows it to the player when the game asks for the microphone with Application.RequestUserAuthorization, and the game records only if Application.HasUserAuthorization returns true. The macOS Player settings have the same field.
Web
Microphone is not supported in the Unity Web player in Unity 6.3 LTS. In Unity 6.6, the Microphone class requires user authorization on Web, and the script requests it via Application.RequestUserAuthorization before use. Since the browser sends the upload, your server also has to allow the game’s origin with CORS headers, unless it’s the server that hosts the game. The servers on this page don’t send CORS headers.
Related
Reading this as an AI agent? The raw Markdown is at integrations/unity.md, and the full index is /resources/llms.txt.
