How to stop audio from playing in flutter

7,053

Solution 1

Have you tried simply player.stop()?

If it doesn't work, then maybe you should try to move AudioPlayer outside from 'playMusic' method, like this:

    AudioPlayer player = new AudioPlayer();
    String mp3Uri = "";

    void _playSound() {
      player.play(mp3Uri);
    }

    void _stopSound() {
      player.stop();
    }

Solution 2

If using AudioCache for playing audio file from assets, here is a solution i found:

  • create a AudioPlayer
  • use it in your AudioCache Instance as a fixedPlayer
  • you can then use stop() method on the AudioPlayer Instance
const timerFinishedAudio = "alarm-sound.mp3";
const audioFilesPrefix = 'audio/';
final audioPlayer = AudioPlayer();

// in your State
static AudioCache player = new AudioCache(prefix: audioFilesPrefix, fixedPlayer: audioPlayer);

// in a function
player.play(timerFinishedAudio);

// in another function or dispose()
audioPlayer.stop();
Share:
7,053
Evelyn
Author by

Evelyn

Updated on December 19, 2022

Comments

  • Evelyn
    Evelyn over 1 year

    My code is meant to play a song when the user presses play sound and I need a button to stop the music from playing. I chose to play the music like this because the audio cache function was not working in my code for some reason (I kept getting an error saying my file couldn't be loaded) though this method works I have no idea on how to stop the music from playing like this.

    import 'dart:io';
    import 'package:audioplayers/audio_cache.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:audioplayers/audioplayers.dart';
    import 'dart:io';
    
    class bodyscan extends StatefulWidget {
      @override
      _bodyscanState createState() => _bodyscanState();
    }
    
    enum PlayerState {stopped,playing,paused}
    
    class _bodyscanState extends State<bodyscan> {
    
      String mp3Uri = "";
      void _playsound(){
        AudioPlayer player = AudioPlayer();
        player.play(mp3Uri);
    
      }
    
      void _loadsound() async {
        final ByteData data = await rootBundle.load("audio/doomed.m4a");
        Directory tempDir = await getTemporaryDirectory();
        File tempFile = File('${tempDir.path}/doomed.m4a');
        await tempFile.writeAsBytes(data.buffer.asUint8List(), flush:true);
        mp3Uri = tempFile.uri.toString();
      }
      @override
      void initState() {
        _loadsound();
        super.initState();
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
    
                  InkWell(
                    enableFeedback: false,
                    child :Container (
                      color: Colors.blue,
                      padding: const EdgeInsets.all(20.0),
                      child: Text('PlaySound', style: TextStyle(color: Colors.white),) ,
    
                    ),
                    onTap: _playsound,
                  ),
                ],
              ),
            )
        );
      }
    }
    
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy over 3 years
    I'm using AudioCache for playing files in local assets folder. audioCache.play() method is there but audioCache.stop() is not there. How to stop song using audioCache ??
  • emvaized
    emvaized over 3 years
    @KPradeepKumarReddy try to assign audioCache variable player to null. Or simply create an AudioPlayer for this AudioCache and use it for control.
  • K Pradeep Kumar Reddy
    K Pradeep Kumar Reddy over 3 years
    Thanks. I'm creating audio player instance for the audio cache and using it for control. Can we know if the player is currently running ?? i'm not able to find any method like audioPlayer.isPlaying(). I want to check if the player is already running then don't play it again. How to achieve this functionality ?
  • emvaized
    emvaized over 3 years
    @KPradeepKumarReddy I don't quite remember, but it seems you can use AudioCache for this and check if it's null or not