Poornima Mishra
Poornima Mishra

Reputation: 416

How to open audio file from file manager and play that audio file using Flutter app

I'm new in flutter development and I got stuck in a program where I want to play an audio file by selecting it from file manager.i am able to open audio file from file manager but I don't know how to play that audio file. Please help me out with this. I am using this code -

import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FilePickerDemo extends StatefulWidget {
@override
_FilePickerDemoState createState() => _FilePickerDemoState();
}

I am using this for file picking and save file I want to know how to play save file

class _FilePickerDemoState extends State<FilePickerDemo> {
void _pickFiles() async {
_resetState();
try {
  _directoryPath = null;
  _paths = (await FilePicker.platform.pickFiles(
    type: _pickingType,
    allowMultiple: _multiPick,
    onFileLoading: (FilePickerStatus status) => print(status),
    allowedExtensions: ['mp3'],
  ))
      ?.files;
} on PlatformException catch (e) {
  _logException('Unsupported operation' + e.toString());
} catch (e) {
  _logException(e.toString());
}
if (!mounted) return;
setState(() {
  _isLoading = false;
  _fileName =
  _paths != null ? _paths!.map((e) => e.name).toString() : '...';
  _userAborted = _paths == null;
});
}

Upvotes: 0

Views: 4002

Answers (2)

Kdon
Kdon

Reputation: 1225

Another handy package is AudioPlayers that can also cache local audio files.

Here is a very basic example, that has buttons to play, pause and stop a reference to local audio that is passed into a stateful widget, to get you started (based mainly off this Medium article) Medium Article

Reminder to save your audio in your local files like below

enter image description here

and add a reference in your yaml file and get dependencies

  assets:
    - assets/audio/
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

class AudioManagerExample extends StatefulWidget {
  const AudioManagerExample({required this.audioName, Key? key}) : super(key: key);

  final String audioName;

  @override
  _AudioManagerExampleState createState() => _AudioManagerExampleState();
}

class _AudioManagerExampleState extends State<AudioManagerExample> {
  AudioPlayer audioPlayer = AudioPlayer();
  late AudioCache audioCache;

  @override
  void initState() {
    audioCache = AudioCache(fixedPlayer: audioPlayer);
    audioCache.load('audio/${widget.audioName}.mp3');
    super.initState();
  }

  @override
  void dispose() {
    audioCache.clearAll();
    audioPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
          onPressed: () {
            setState(() {
              audioCache.play('audio/${widget.audioName}.mp3');
            });
          },
          child: Text('Play ${widget.audioName}'),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              audioPlayer.pause();
            });
          },
          child: Text('Pause ${widget.audioName}'),
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              audioPlayer.stop();
            });
          },
          child: Text('Stop ${widget.audioName}'),
        ),
      ],
    );
  }
}


Upvotes: 0

Chirag Kothiya
Chirag Kothiya

Reputation: 1099

You can use https://pub.dev/packages/just_audio package to play audio.

import 'package:just_audio/just_audio.dart';

final _player = AudioPlayer();
    

playAudio() async {
    try {
      await _player.setFilePath(widget.audioPath);
    } catch (e) {
      log("Error loading audio source: $e");
    }
    _player.play();
  }

Upvotes: 1

Related Questions