Flutter audio_service play audio in background when mobile screen is locked

2.3k views Asked by At

I made a radio player app with the code below. Everything works fine when the mobile screen is turned on. But when i turn off my mobile screen the radio stops playing at about 5-8 minutes. I got some tips about using flutter audio_service. (https://pub.dev/packages/audio_service) But i am confused from where should i start. Should i recode again or i can modify this code. Somebody please help me. It would be a grace. Thankyou in advance.

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

class Radio1 extends StatefulWidget {
  @override
  _Radio1State createState() => _Radio1State();
}

class _Radio1State extends State<Radio1> {
  AudioPlayer audioPlayer = AudioPlayer();

  @override
  void initState() {
    super.initState();
    AudioPlayer.logEnabled = true;
  }

  bool _isPlaying = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              //new
              SizedBox(
                height: 50,
              ),

              //Icon(
              // Icons.arrow_drop_down,
              //size: 40,
              //),

              //new
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20, vertical: 50),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0x46000000),
                      offset: Offset(0, 20),
                      spreadRadius: 0,
                      blurRadius: 30,
                    ),
                    BoxShadow(
                      color: Color(0x11000000),
                      offset: Offset(0, 10),
                      spreadRadius: 0,
                      blurRadius: 30,
                    ),
                  ],
                ),
//new
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(20),
                  child: Image(
                    image: AssetImage("assets/radiologo.jpg"),
                    width: MediaQuery.of(context).size.width * 0.7,
                    height: MediaQuery.of(context).size.width * 0.7,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Text(
                "sample text",
                style: TextStyle(fontSize: 30, fontWeight: FontWeight.w500),
              ),
              Text(
                "(sample text)",
                style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500),
              ),
              /* Slider(
                value: 10,
                onChanged: (v) {},
                max: 170,
                min: 0,
                activeColor: Color(0xFF5E35B1),
              ), */
              Text(
                "sample text.",
                style: TextStyle(fontSize: 10, fontWeight: FontWeight.w500),
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    icon: _isPlaying == false
                        ? Icon(Icons.play_circle_outline)
                        : Icon(Icons.pause_circle_outline),
                    iconSize: 60.0,
                    onPressed: () {
                      getAudio();
                    },
                  ),
                  IconButton(
                    icon: Icon(Icons.stop),
                    iconSize: 40,
                    onPressed: () {
                      stopAudio();
                    },
                  ),
                  //new line
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void getAudio() async {
    var url = "http://ia802708.us.archive.org/3/items/count_monte_cristo_0711_librivox/count_of_monte_cristo_001_dumas.mp3";
    if (_isPlaying) {
      var res = await audioPlayer.pause();
      if (res == 1) {
        setState(() {
          _isPlaying = false;
        });
      }
    } else {
      var res = await audioPlayer.play(url);
      if (res == 1) {
        setState(() {
          _isPlaying = true;
        });
      }
    }
  }

  void stopAudio() async {
    int res = await audioPlayer.stop();

    if (res == 1) {
      setState(() {
        _isPlaying = false;
      });
    }
  }

  void releaseAUdio() async {
    await audioPlayer.stop();
    await audioPlayer.release();
  }

  @override
  void dispose() {
    super.dispose();
    releaseAUdio();
  }
}
1

There are 1 answers

0
hpapier On

So as you use the audioplayers package, you'll need to implement the audio_service one to achieve what you want (playing audio in background). Indeed, the audioplayers package is only responsible for playing audio files, and does not handle the background behaviours.

The audio_service is designed to be the only source of truth in your application. So you'll need to re-architecture your code to fit.

But don't delete your code, you might not need many changes in it for the audio. The package is cut in multiple parts. For example, one for the background tasks, one for the UI to tell the background tasks what you want to do (play, pause, seekTo, ...), so the only changes you might need to do in your code will be to call this part, called AudioService (check the API reference for more informations: https://pub.dev/documentation/audio_service/latest/audio_service/AudioService-class.html).

Once you did that, of course you'll have to implement your background task to achieve your needs.

In summary:

  1. Your code is good, but does not handle the background behaviours.
  2. You may need to implement the audio_service package (or a similar one) to handle the background behaviours.
  3. Please take a look at the audio_session package too to handle the interactions between your app and the different audio interactions on the phone. (For example, handle the notifications received and decrease the volume of your app in consequence).

Hope this answer is helpful for you, good luck :)