---
title: "Add music recognition to a Flutter app"
description: "Record a few seconds of audio in a Flutter app with the record package, upload it to your own server, and show the song AudD found, with microphone permissions on iOS and Android, the no-match case, errors and offline handling."
slug: "/resources/integrations/flutter"
section: "integrations"
keywords: [audd, flutter, dart, music recognition, song recognition, record package, microphone, ios, android, mobile app]
---

# Add music recognition to a Flutter app

You can add song recognition to a Flutter app. When the user taps a button, it records 10 seconds from the microphone and sends the recording to your server. 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 app shows them on the screen. The code on this page is for iOS and Android.

> **Don't put your API token in the app.** You can share the results with your users, but please don't include your API tokens in the client-side software. If you put your token in an app, anyone who has a copy of the app can use the token to access the AudD API with your account. For the reasons, and for the server this page uses, see [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side).

## How it works

The app records 10 seconds of audio with the `record` package 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 app shows. If there are no matches, the app asks the user to try again.

## What you need

- Flutter 3.44 or later. The `record` package needs it: version 7.2.0 requires Flutter 3.44 and Dart 3.12. The current stable release, in November 2026, is Flutter 3.50.1.
- An API token. You can get a token from our [API Dashboard](https://dashboard.audd.io). For a first try, the public `test` token allows 10 requests a day.
- Node.js 20 or later for the server.

## Run the server

You can use the server from [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side). It's a single file, `server.ts`, that uses Express, `multer`, and our Node SDK. Copy it from that page, install the dependencies, and start it with your API token:

```bash
npm install @audd/sdk express multer
AUDD_API_TOKEN=your-api-token npx tsx server.ts
```

In another terminal, send it a URL or a file:

```bash
curl -F url=https://audd.tech/example.mp3 http://localhost:3000/identify
curl -F file=@clip.m4a http://localhost:3000/identify
```

For the example URL, the answer is:

```json
{"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 listens on port 3000 and has one route, `POST /identify`. It accepts a file in the `file` parameter or a link in the `url` parameter, as multipart/form-data. These are the answers the app reads:

| Status | Body | Meaning |
|---|---|---|
| 200 | `{"match": true, ...}` | a song was found |
| 200 | `{"match": false}` | no match |
| 413 | `{"error": "LIMIT_FILE_SIZE"}` | the file is over 10 MB |
| 422 | `{"error": "unreadable_audio"}` | the audio can't be read |
| 429 | `{"error": "too_many_requests"}` | over 20 requests an hour from one IP |
| 502 | `{"error": "recognition_failed"}` | any other error (details in the server log) |

We also have the same server in C#, built on our .NET SDK, on the [Unity page](/resources/integrations/unity#the-server). You can use it with this app. Note that it listens on `localhost` in the example there; start it with `--urls http://0.0.0.0:3000` if you're testing on a phone.

## Add the packages

```bash
flutter pub add record http path_provider url_launcher
```

The `record` package records the clip, and `http` uploads it to your server. `path_provider` finds a temporary folder for the recording, and `url_launcher` opens the song's link. These are the current versions on pub.dev as of November 2026: record 7.2.0, http 1.6.0, path_provider 2.1.6 and url_launcher 6.3.3.

## Permissions

### iOS

Add the following key to `ios/Runner/Info.plist`. The string is the message iOS shows when the app asks for the microphone:

```xml
<key>NSMicrophoneUsageDescription</key>
<string>The app listens for 10 seconds to identify the song that's playing.</string>
```

The `record` package supports iOS 12.0 and later.

### Android

Add the permissions to `android/app/src/main/AndroidManifest.xml`, inside `<manifest>` and before `<application>`:

```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
```

Android apps must declare the permissions they use in the manifest, including the use of the internet. The `record` package needs Android API level 24 or higher. You don't have to request the microphone permission yourself: `hasPermission()` asks the user the first time the app records.

## Record a clip and send it

Create a file named `lib/identify.dart` with the following content. Then change the address in `identifyUrl` to the address of your server.

```dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:record/record.dart';

/// Your server's address. The AudD token lives there, not in the app.
final identifyUrl = Uri.parse('https://your-server.example/identify');

/// The standard endpoint analyzes up to the first 12 seconds of audio.
const clipLength = Duration(seconds: 10);

sealed class IdentifyResult {
  const IdentifyResult();
}

class SongFound extends IdentifyResult {
  const SongFound({
    required this.artist,
    required this.title,
    this.album,
    this.songLink,
  });

  final String artist;
  final String title;
  final String? album;
  final String? songLink;
}

class NoMatch extends IdentifyResult {
  const NoMatch();
}

class IdentifyFailed extends IdentifyResult {
  const IdentifyFailed(this.message);

  final String message;
}

/// Records [clipLength] of audio to a temporary .m4a file and returns its
/// path, or null if the user didn't allow the microphone.
/// Throws a PlatformException if the recording can't start.
Future<String?> recordClip(AudioRecorder recorder) async {
  if (!await recorder.hasPermission()) return null;
  final dir = await getTemporaryDirectory();
  await recorder.start(
    const RecordConfig(encoder: AudioEncoder.aacLc, numChannels: 1),
    path: '${dir.path}/clip.m4a',
  );
  await Future<void>.delayed(clipLength);
  return recorder.stop();
}

/// Uploads the clip to your server, deletes it, and returns the answer.
Future<IdentifyResult> identifyClip(String path) async {
  try {
    final request = http.MultipartRequest('POST', identifyUrl)
      ..files.add(await http.MultipartFile.fromPath('file', path));
    final streamed = await request.send().timeout(const Duration(seconds: 30));
    return _read(await http.Response.fromStream(streamed));
  } on TimeoutException {
    return const IdentifyFailed('The server took too long to answer. Try again.');
  } on Exception {
    // No connection, or the server is down.
    return const IdentifyFailed(
        "Couldn't reach the server. Check your connection and try again.");
  } finally {
    File(path).delete().ignore(); // don't keep the recording
  }
}

IdentifyResult _read(http.Response response) {
  if (response.statusCode != 200) {
    return IdentifyFailed(switch (response.statusCode) {
      422 => "Couldn't read that recording. Try again.",
      429 => 'Too many tries. Wait a while and try again.',
      _ => 'Something went wrong (${response.statusCode}). Try again later.',
    });
  }
  Object? body;
  try {
    body = jsonDecode(response.body);
  } on FormatException {
    body = null;
  }
  if (body is Map<String, dynamic>) {
    if (body['match'] == false) return const NoMatch();
    if (body['match'] == true) {
      return SongFound(
        artist: _text(body['artist']) ?? '',
        title: _text(body['title']) ?? '',
        album: _text(body['album']),
        songLink: _text(body['songLink']),
      );
    }
  }
  return const IdentifyFailed('Something went wrong. Try again later.');
}

String? _text(Object? value) => value is String ? value : null;
```

The standard endpoint analyzes up to the first 12 seconds of audio, so the app records 10 seconds (it usually takes less than 200 KB). It records mono AAC in an M4A file at the package's default bit rate, 128 kbps, and the standard endpoint accepts files up to 10 MB. M4A is one of the formats we support, so you don't need to convert the file.

The file is sent with `MultipartFile.fromPath`, which reads it from disk while it's being uploaded. If the server doesn't answer within 30 seconds, the request times out. When the upload is finished, the recording is deleted.

## Show the result

Replace the contents of the file `lib/main.dart` with the following:

```dart
import 'package:flutter/material.dart';
import 'package:record/record.dart';
import 'package:url_launcher/url_launcher.dart';

import 'identify.dart';

void main() => runApp(const MaterialApp(home: SongIdPage()));

class SongIdPage extends StatefulWidget {
  const SongIdPage({super.key});

  @override
  State<SongIdPage> createState() => _SongIdPageState();
}

class _SongIdPageState extends State<SongIdPage> {
  final _recorder = AudioRecorder();
  var _busy = false;
  var _status = 'Play some music and tap Identify.';
  SongFound? _song;

  @override
  void dispose() {
    _recorder.dispose();
    super.dispose();
  }

  void _show(String status, {bool busy = false, SongFound? song}) {
    if (!mounted) return;
    setState(() {
      _status = status;
      _busy = busy;
      _song = song;
    });
  }

  Future<void> _identify() async {
    _show('Listening...', busy: true);
    String? path;
    try {
      path = await recordClip(_recorder);
    } on Exception {
      _show("Couldn't record from the microphone.");
      return;
    }
    if (path == null) {
      _show('Allow microphone access in Settings to identify songs.');
      return;
    }

    _show('Looking it up...', busy: true);
    switch (await identifyClip(path)) {
      case SongFound song:
        _show('', song: song);
      case NoMatch():
        _show('No match. Move closer to the music and try again.');
      case IdentifyFailed(:final message):
        _show(message);
    }
  }

  @override
  Widget build(BuildContext context) {
    final song = _song;
    final link = song?.songLink;
    return Scaffold(
      appBar: AppBar(title: const Text('What song is this?')),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (song != null) ...[
                Text(song.title,
                    style: Theme.of(context).textTheme.headlineSmall,
                    textAlign: TextAlign.center),
                Text(song.artist, textAlign: TextAlign.center),
                if (link != null)
                  TextButton(
                    onPressed: () => launchUrl(Uri.parse(link),
                        mode: LaunchMode.externalApplication),
                    child: const Text('Open the song'),
                  ),
              ],
              Text(_status, textAlign: TextAlign.center),
              const SizedBox(height: 24),
              FilledButton(
                onPressed: _busy ? null : _identify,
                child: const Text('Identify'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
```

Now you can run the app. Play a song near the phone and tap Identify: the button is disabled while the app is listening. After about 10 seconds, you'll see the title and artist of the song, and a button that opens the song's lis.tn page, which links to the streaming platforms.

## 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 app shows "No match". It's not an error, so there's nothing to retry automatically: let the user tap Identify again. If the music was quiet, or the recording was mostly talking, ask the user to move the phone closer to the speaker.

## When something goes wrong

### When the phone is offline

If the phone is offline or the app can't connect to your server, `send()` throws a `ClientException`. The app asks the user to check the internet connection and try again. If your server doesn't answer within 30 seconds, the app stops waiting and asks the user 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 user denies the permission, `hasPermission()` returns `false`, and the app asks them to allow it in Settings. If the recording can't start, `start()` throws a `PlatformException`, and the app shows that it couldn't record.

### 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](/resources/reference/errors) page explains what our errors mean.

## Test it on an emulator or a phone

If you're testing in the Android emulator, set `identifyUrl` to `http://10.0.2.2:3000/identify`. The emulator uses 10.0.2.2 for your computer, so the app can reach the server on port 3000. If you're testing on a phone, use the IP address of your computer on your local network instead. For the release build, put the server online and use its HTTPS address.

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](/resources/concepts/testing-your-integration).

---

**Related**

- [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side)
- [Add music recognition to a React Native app](/resources/integrations/react-native)
- [Add music recognition to a Unity game](/resources/integrations/unity)
- [Audio formats and quality for music recognition](/resources/concepts/audio-format-and-quality)
- [Production checklist](/resources/concepts/production-checklist)
- [API reference](https://docs.audd.io)

## Sitemap

See the [resources sitemap](https://audd.io/resources/sitemap.md) for every guide and the [glossary](https://audd.io/resources/reference/glossary.md) for AudD terms.
