dartweb-audio-apidart-html

How can I use AudioContext on Dart 2.16 and plus?


How can I use AudioContext on Dart 2.16 ? Because I couldn't import the dart:web_audio library.


Solution

  • You can use this class by implementing it. For this, you have to install the js_bindings package.

    import 'dart:convert';
    import 'package:flutter_webrtc/flutter_webrtc.dart' as webrtc;
    import 'package:dart_webrtc/src/media_stream_track_impl.dart' as track_impl;
    import 'package:js_bindings/js_bindings.dart' as js_bindings;
    import 'package:universal_html/html.dart' as html;
    import 'dart:js_util' as js_util;
    
    class JsAudioContext {
      js_bindings.AudioContext? audioContext;
      js_bindings.MediaStreamAudioDestinationNode? destinationNode;
      JsAudioContext() {
        audioContext = js_bindings.AudioContext();
      }
    
      void createMediaStreamDestination() {
        destinationNode = audioContext?.createMediaStreamDestination();
      }
    
      void connect(webrtc.MediaStreamTrack? trackWeb) {
        track_impl.MediaStreamTrackWeb mediaStreamTrackWeb =
            trackWeb as track_impl.MediaStreamTrackWeb;
        html.MediaStreamTrack htmlTrack = mediaStreamTrackWeb.jsTrack;
        var sourceStream = audioContext?.createMediaStreamSource(
            js_bindings.MediaStream([htmlTrack as js_bindings.MediaStreamTrack]));
        sourceStream?.connect(destinationNode!);
      }
    
      webrtc.MediaStreamTrack getMixedTrack() {
        List<dynamic> outputTrack =
            js_util.callMethod(destinationNode!.stream, 'getTracks', []);
    
        webrtc.MediaStreamTrack rtcTrack = track_impl.MediaStreamTrackWeb(
            outputTrack.toList()[0] as html.MediaStreamTrack);
        return rtcTrack;
      }
    }