Fabrizio
Fabrizio

Reputation: 1074

Play a Custom Sound in Flutter

I'm trying to Play a custom mp3 sound I've put in an asset folder into the app folder, like you would do for a font or an image file, but then I don't really know how to proceed. I think I might need to register the audio file into the pubspec.yaml, but how?

And how do I play it?

I've checked out this two answer: How to play a custom sound in Flutter?

Flutter - Play custom sounds updated?

But the first one is too old and the second one uses URLs as the sound path: const kUrl2 = "http://www.rxlabz.com/labz/audio.mp3"; and the sound I like to play is in the app, not online. So... How can I do it?

This Is My Current Code, as You can see, there's only a Floating Button. And I need To Start The Sound at the Point I stated it in the code.

But visual studio underlines in red Various Parts: await: it says that await is unrecognized. audioPlugin.play: is says It's also unrecognized

import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());

Directory tempDir = await getTemporaryDirectory();
File tempFile = new File('${tempDir.path}/demo.mp3');
await tempFile.writeAsBytes(bytes, flush: true);
AudioPlayer audioPlugin = new AudioPlayer();


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


  void _incrementCounter() {
    setState(() {
      print("Button Pressed");

      ///
      /// 
      /// 
      /// Here I Need To start Playing the Sound
      /// 
      /// 
      /// 
      /// 
      audioPlugin.play(tempFile.uri.toString(), isLocal: true);

    });
  }



  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 3

Views: 11503

Answers (2)

Jithin
Jithin

Reputation: 101

Use the audioplayers package => https://pub.dev/packages/audioplayers

Add the key to plist for iOS Support

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Add dependencies to pubspec.yaml file

audioplayers: ^0.13.2

Flutter code:

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

class AudioTest extends StatefulWidget {
  @override
  _AudioTestState createState() => _AudioTestState();
}

class _AudioTestState extends State<AudioTest> {

  static AudioCache _player = AudioCache();
  static const _audioPath = "count_down.mp3";
  AudioPlayer _audioPlayer = AudioPlayer();

  Future<AudioPlayer> playAudio() async {
    return _player.play(_audioPath);
  }

  void _stop(){
    if (_audioPlayer != null) {
      _audioPlayer.stop();
  }

  @override
  void initState() {

    playAudio().then((player) {
      _audioPlayer = player;
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return homeScreen();
  }

  Widget homeScreen() {
    return Scaffold();
    //Enter your code here
  }
}

Upvotes: 2

Richard Heap
Richard Heap

Reputation: 51682

It's not pretty, but...

Add the mp3 file to the assets folder and add it to pubspec.yaml like this.

Load the asset as binary data with rootBundle.load(asset)

Use path_provider to get the app's temp folder location

Use regular dart:io to open a file in tempDir (maybe use the asset name) and write bytes to it.

Form a file URL from the temporary file name in the form file:///folderPath/fileName

Pass this to audioplayer, setting isLocal to true (needed on iOS).

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:audioplayer/audioplayer.dart';
import 'package:path_provider/path_provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Audio Player Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  AudioPlayer audioPlugin = AudioPlayer();
  String mp3Uri;

  @override
  void initState() {
    _load();
  }

  Future<Null> _load() async {
    final ByteData data = await rootBundle.load('assets/demo.mp3');
    Directory tempDir = await getTemporaryDirectory();
    File tempFile = File('${tempDir.path}/demo.mp3');
    await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
    mp3Uri = tempFile.uri.toString();
    print('finished loading, uri=$mp3Uri');
  }

  void _playSound() {
    if (mp3Uri != null) {
      audioPlugin.play(mp3Uri, isLocal: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Audio Player Demo Home Page'),
      ),
      body: Center(),
      floatingActionButton: FloatingActionButton(
        onPressed: _playSound,
        tooltip: 'Play',
        child: const Icon(Icons.play_arrow),
      ),
    );
  }
}

Upvotes: 4

Related Questions