Home > Back-end >  Using audioplayers to play a single note from a button
Using audioplayers to play a single note from a button

Time:07-09

I am doing an outdated tutorial on the audioplayers package and just trying to play a single note from when the button is pressed. I am not able to get it to work, can someone please help

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

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

class XylophoneApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: TextButton(
              onPressed: () {
                final player = AudioCache();
                player.play('note1.wav'); //ERROR THAT 'play' method is not valid
              },
              child: Text('Click Me'),
            ),
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

In order to play sound from assets, you need a AudioPlayer and set asset to it.

onPressed: () async {
    final player = AudioPlayer();
    await player.setAsset('note1.wav'); // make sure to add on pubspec.yaml and provide correct path
    player.play();
  }

CodePudding user response:

Finally found the fix, the problem all had to do with the new version of audioplayers having all the functions in one class without having to import seperatly audiocache

onPressed: () {
   final player = AudioPlayer();
   player.play(AssetSource("note1.wav"));
}
  • Related