How to play audio in flutter

93 Views Asked by At

Im trying to make a meditation page, when you click on start, it will start the timer and sound will be playing. I cant play the sound, it's showing many error. I have tried many ways. Please help me to play the sound, or if you have any other methods then please provide.

import 'dart:async';

import 'package:ableeasefinale/pages/UI/navigationBar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

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

  @override
  State<MedPage> createState() => _MedPageState();
}

class _MedPageState extends State<MedPage> {
  static const maxSeconds = 60;
  int seconds = maxSeconds;
  bool medStart = false;
  String meditationTime = "1 Minutes";
  Timer? timer;
  final player = AudioPlayer();
  
  void startTimer() {
    player.play(AssetSource('medAudio.mp3'));;
    timer = Timer.periodic(Duration(seconds: 1), (_) {
      if (seconds > 0) {
        setState(() {
          seconds--;
        });
      } else {
        stopTimer(reset: false);
      }
    });
  }

  void resetTimer()  => setState(() {
        seconds = maxSeconds;
        medStart = false;
       player.stop();
      });
  void stopTimer({bool reset = true})  {
    setState(()  {
       player.stop();
      medStart == false;
      resetTimer();
      timer?.cancel();
    });
  }

  @override
  Widget build(BuildContext context) {
    return !medStart
        ? Scaffold(
            backgroundColor: Theme.of(context).colorScheme.background,
            body: Column(
              children: [
                Center(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 150),
                    child: Text(
                      "Meditation",
                      style: TextStyle(
                          color: Theme.of(context).colorScheme.onPrimary,
                          fontSize: 35),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 80),
                  child: Container(
                    height: 250,
                    width: 250,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                      shape: BoxShape.circle,
                      boxShadow: [
                        new BoxShadow(
                          offset: Offset(2, 2),
                          color: Colors.black,
                          blurRadius: 5.0,
                        ),
                      ],
                    ),
                    child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Image(
                          image: AssetImage('lib/assets/images/meditating.png'),
                        )),
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(top: 20),
                  child: DropdownButton<String>(
                    itemHeight: 50.0,
                    value: meditationTime,
                    icon: const Icon(Icons.keyboard_arrow_down_rounded),
                    style: TextStyle(
                        color: Theme.of(context).colorScheme.onSecondary,
                        fontSize: 22),
                    underline: Container(
                      height: 2,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        meditationTime = newValue!;
                      });
                    },
                    items: [
                      DropdownMenuItem(
                        value: '1 Minutes',
                        child: Text('1 Minutes'),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 20),
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(context).colorScheme.primary),
                    onPressed: () {
                      setState(() {
                        medStart = true;
                        
                        startTimer();
                      });
                    },
                    child: Column(
                      children: [
                        Text(
                          "Start",
                          style: TextStyle(color: Colors.white, fontSize: 20),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        : Scaffold(
            backgroundColor: Theme.of(context).colorScheme.background,
            body: Column(
              children: [
                Center(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 150),
                    child: Text(
                      "Meditation",
                      style: TextStyle(
                          color: Theme.of(context).colorScheme.onPrimary,
                          fontSize: 35),
                    ),
                  ),
                ),
                Container(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 80),
                    child: Column(children: [
                      SizedBox(
                        width: 250,
                        height: 250,
                        child: Stack(
                          fit: StackFit.expand,
                          children: [
                            CircularProgressIndicator(
                              color: Theme.of(context).colorScheme.secondary,
                              value: seconds / maxSeconds,
                            ),
                            Container(
                              height: 250,
                              width: 250,
                              child: Padding(
                                padding: const EdgeInsets.all(15.0),
                                child: Image(
                                    image: AssetImage(
                                        "lib/assets/images/meditating.png")),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 30,
                      ),
                      Text('$seconds'),
                    ]),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 20),
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(context).colorScheme.primary),
                    onPressed: () {
                      setState(() {
                        medStart = false;
                        stopTimer();
                      });
                    },
                    child: Column(
                      children: [
                        Text(
                          "STOP",
                          style: TextStyle(color: Colors.white, fontSize: 20),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
  }
}

Error:

E/flutter ( 7638): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: "assets/medAudio.mp3".

E/flutter ( 7638): The asset does not exist or has empty data.

E/flutter ( 7638): #0      PlatformAssetBundle.load.<anonymous closure> (package:flutter/src/services/asset_bundle.dart:324:9)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #1      AudioCache.fetchToMemory (package:audioplayers/src/audio_cache.dart:89:22)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #2      AudioCache.load (package:audioplayers/src/audio_cache.dart:120:31)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #3      AudioCache.loadPath (package:audioplayers/src/audio_cache.dart:129:26)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #4      AudioPlayer.setSourceAsset (package:audioplayers/src/audioplayer.dart:360:23)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #5      AudioPlayer.setSource (package:audioplayers/src/audioplayer.dart:300:5)

E/flutter ( 7638): <asynchronous suspension>

E/flutter ( 7638): #6      AudioPlayer.play (package:audioplayers/src/audioplayer.dart:195:5)

E/flutter ( 7638): <asynchronous suspension>
E/flutter ( 7638): 

Pubspec.yaml - assets Pubspec.yaml

Lib Structure

2

There are 2 best solutions below

8
K.D.Dilshan On BEST ANSWER

You should add those assets into pubspec.yaml file like bellow

flutter:

  assets:
    - images/example.png
    - assets/example.mp3
  • after adding those assets run flutter clean command and then run flutter pub get
  • and you should keep you'r assets folder in your project level I add image look at this.

enter image description here

2
Leo Tran On

As mentioned above you should add the audio file in the pubspec.ymal and need to run pub get to update the file.

I’m updating my mediation app too, may I know if you try to play the audio in background/ lock screen? I used other package and really want to move to just audio and audio service if they support these features.