Daniel Oyebode
Daniel Oyebode

Reputation: 1

Unable to play sound with AudioPlayer package

I am trying to play a sound from my asset directory in dart, I have added the required lines of code and also included the asset directory in pubspec.yaml.

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

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: TextButton(
                onPressed: () {
                  AudioPlayer player = AudioPlayer();

                  player.play(DeviceFileSource('note1.wav'));
                },
                child: Text('Click Me'),
            ),
          ),
        ),
      ),
    )
  );
}

Upvotes: 0

Views: 763

Answers (2)

You have to use AssetSource for this because as per the documentation of AudioPlayer:

  1. DeviceFileSource: [is used to] access a file in the user's device, probably selected by a file picker
  2. AssetSource: [is used to] play an asset bundled with your app, normally within the assets directory

Don't worry, this gave me some grief too and the answer above pointed me in the right direction. I just wanted to take an extra step to understand why, hope this helps!

Upvotes: 0

Khalid Alhazmi
Khalid Alhazmi

Reputation: 61

Try to change the source of the audio by using AssetSource() and make sure to add the source of your audio in the yaml file

onPressed: () {
    AudioPlayer player = AudioPlayer();
    player.play(AssetSource('audio.mp3'));
},

Upvotes: 2

Related Questions