dartaudiobrowserwavdart-html

How to play a sound (wav) in Dart?


I use a Dart script in a web page and need to play a WAV file in the browser when a certain event is triggered. I do not use Flutter. Instead, it is a simple DOM-interacting program. What I’m looking for is basically the Dart counterpart of the following JavaScript:

function playSound(url) {
  const audio = new Audio(url);
  audio.play();
}

Solution

  • One can play a sound from a URL by writing:

    import "dart:html";
    final clickSound = new AudioElement("https://example.com/mysound.wav");
    clickSound.play();
    

    One can reuse clickSound for playing it as often as you need.