How to play an audio file and url in flutter?

By the top of this tutorial, you’ll be ready to add a music player as shown within the video in your own flutter app.

How to play an audio file in flutter?

For this tutorial, we’ll use two packages.

  • audio players package – This package actually does most of the a part of our tutorial. it’ll allow us to play audio, pause, stop & resume. you’ll also seek through the duration. However, for the sake of keeping the tutorial short & simple, I even have excluded it.
  • file_picker package – This package will allow us to select audio (it works for other file types too) from our local storage and generate its path.

STEPS TO FOLLOW:

Add both the package dependencies as shown here

dependencies:
  flutter:
    sdk: flutter
  audioplayers: ^0.14.1
  file_picker: ^1.2.0
  • However, it worked fine on my android device without adding any permissions but just just in case you see errors piling up, try adding permissions for android and/or iOS for the file_picker plugin. you’ll find the permissions to be added on the package’s official docs on pub.dev
  • Finally, paste this complete code in your main.dart file to realize an equivalent results as shown within the video above.
import 'package:file_picker/file_picker.dart';

import 'package:flutter/material.dart';

import 'package:audioplayers/audioplayers.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override

  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AudioPlayer',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Audio Player'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isPlaying = false;
  AudioPlayer audioPlayer;
  @override

  void initState() {
    super.initState();
    audioPlayer = AudioPlayer();
  }
  playAudioFromLocalStorage(path) async {
    int response = await audioPlayer.play(path, isLocal: true);
    if (response == 1) {
      // success

    } else {
      print('Some error occured in playing from storage!');
    }
  }
  pauseAudio() async {
    int response = await audioPlayer.pause();
    if (response == 1) {
      // success

    } else {
      print('Some error occured in pausing');
    }
  }
  stopAudio() async {
    int response = await audioPlayer.stop();
    if (response == 1) {
      // success

    } else {
      print('Some error occured in stopping');
    }
  }
  resumeAudio() async {
    int response = await audioPlayer.resume();
    if (response == 1) {
      // success

    } else {
      print('Some error occured in resuming');
    }
  }
  @override

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Container(
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      RaisedButton(
                        onPressed: () {
                          if (_isPlaying == true) {
                            pauseAudio();
                            setState(() {
                              _isPlaying = false;
                            });
                          } else {
                            resumeAudio();
                            setState(() {
                              _isPlaying = true;
                            });
                          }
                        },
                        child:
                            Icon(_isPlaying ? Icons.pause : Icons.play_arrow),
                        color: Colors.blue,
                      ),
                      RaisedButton(
                        onPressed: () {
                          stopAudio();
                          setState(() {
                            _isPlaying = false;
                          });
                        },
                        child: Icon(Icons.stop),
                        color: Colors.blue,
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                RaisedButton(
                  onPressed: () async {
                    var path =
                        await FilePicker.getFilePath(type: FileType.audio);
                    setState(() {
                      _isPlaying = true;
                    });
                    playAudioFromLocalStorage(path);
                  },
                  child: Text(
                    'Load Audio File',
                    style: TextStyle(color: Colors.white),
                  ),
                  color: Colors.blueAccent,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

How to play an audio URL in flutter?

You Can Also play from Url just add url in audioPlayer.play(‘your url here’);

Method 2

The audioplayer plugin currently only supports network paths and files. You can move an asset to a temporary folder and play it with this code:

import 'package:path_provider/path_provider.dart';

final file = new File('${(await getTemporaryDirectory()).path}/music.mp3');
await file.writeAsBytes((await loadAsset()).buffer.asUint8List());
final result = await audioPlayer.play(file.path, isLocal: true);

Method 3

assets_audio_player 2.0.7+9 use this music player, Where you can play music from the network as well as from assets folder. And Also you don’t need to handle it in the background.

    AudioPlayer _audioPlayer = AudioPlayer();

  play() async {
    int result = await _audioPlayer.play('http://thedemos.in/mind/uploads/audio/WjYYX_Namaste2.mp3');
    if (result == 1) {
      setState(() {
        isPlaying = true;
      });
      print('Success');
    }
  }

Summery

So it’s all About All possible solutions. Hope this above all solution helped you a lot. Comment below Your thoughts and your queries. Comment Below on your suggestion.

Check Out Below Article

TypeError: this.getOptions is not a function in vue.js

Leave a Comment

x