Skip to main content

Command Palette

Search for a command to run...

Connecting Flutter App To Bluetooth Audio Speaker

Updated
2 min read
M

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).

[1] Create a new Flutter Project

flutter create connectbluespeaker1
cd connectbluespeaker1

[2] Add Flutter Package

flutter pub add audioplayers

[3] Edit Main

The code will get an audio file from the Internet and the plays it.

import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: AudioPage(),
    );
  }
}

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

  @override
  State<AudioPage> createState() => _AudioPageState();
}

class _AudioPageState extends State<AudioPage> {
  final AudioPlayer player = AudioPlayer();
  bool isPlaying = false;

  Future<void> playAudio() async {
    await player.play(
      UrlSource('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'),
    );

    setState(() {
      isPlaying = true;
    });
  }

  Future<void> stopAudio() async {
    await player.stop();

    setState(() {
      isPlaying = false;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Bluetooth Speaker Player"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              isPlaying ? Icons.music_note : Icons.music_off,
              size: 80,
            ),
            const SizedBox(height: 20),

            ElevatedButton(
              onPressed: playAudio,
              child: const Text("Play"),
            ),

            ElevatedButton(
              onPressed: stopAudio,
              child: const Text("Stop"),
            ),
          ],
        ),
      ),
    );
  }
}

[4] Edit Android Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Needed for streaming audio -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <application
        android:label="connectbluespeaker1"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">

        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:taskAffinity=""
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>

</manifest>

Outcome

7 views