Microphone Access on Flutter Web with getUserMedia and package:web
Capture the microphone in a Flutter web app with package:web getUserMedia, audio constraints, Safari quirks, and cleanup of MediaStream tracks.
Published on • November 10, 2026
AI Assistant

Voice input, dictation, and audio notes all start with the same browser call, getUserMedia, and on Flutter web it fails for reasons that never appear on mobile: insecure origins, Permissions Policy headers, or an iOS Safari quirk. This post shows how to request the microphone through package:web, set constraints that matter, stream audio into speech-to-text pipelines, and release the hardware cleanly.
Secure context and the permission prompt
getUserMedia is available only in secure contexts - HTTPS or localhost - and outside one, navigator.mediaDevices is undefined, so the call itself throws a TypeError before any permission UI appears. Permission is always required, and browsers must show an indicator while the microphone is in use. The promise can also never settle if the user simply dismisses the prompt, so build your UI around that possibility rather than a fixed timeout alone.
Two failure modes are easy to miss. First, Permissions Policy: the microphone directive governs access, defaulting to the top-level document, so an embedded app needs Permissions-Policy: microphone=(self) from the server and allow="microphone" on the iframe. Second, error mapping: a denial arrives as a NotAllowedError (also raised for insecure contexts and policy blocks), no device as NotFoundError, a busy device as NotReadableError, and impossible constraints as OverconstrainedError.
Getting a MediaStream with package:web
With dart:html deprecated, the modern path is package:web plus dart:js_interop. MediaDevices.getUserMedia mirrors the Web IDL: it takes an optional MediaStreamConstraints and returns a JSPromise<MediaStream>:
dependencies:
web: ^1.1.2
import 'dart:js_interop';
import 'package:web/web.dart' as web;
web.MediaStream? _mic;
Future<bool> startMic() async {
try {
_mic = await web.window.navigator.mediaDevices
.getUserMedia(web.MediaStreamConstraints(audio: true.toJS))
.toDart;
return true;
} catch (e) {
// NotAllowedError, NotFoundError, or an insecure context
return false;
}
}
Convert Dart values with .toJS on the way in and .toDart on the promise on the way out. Keep the MediaStream reference: you will need it to stop the hardware later.
Constraints that matter
Passing audio: true gets you defaults; real apps usually want tuning. package:web’s MediaTrackConstraints exposes the standard audio fields, including echoCancellation, autoGainControl, noiseSuppression, sampleRate, channelCount, latency, and deviceId. Constraint semantics follow the W3C rules: plain values and ideal are preferences the browser may ignore, while min, max, and exact are mandatory - an unsatisfiable exact rejects with OverconstrainedError before prompting, which is why device enumeration and ideal are safer defaults for a shipped feature. For voice chat, echoCancellation: true and noiseSuppression: true are the two that most change perceived quality; the record package’s feature matrix confirms echo cancellation is supported on its web implementation.
Consuming the stream in Dart
Two routes feed audio into Dart. The simple one is MediaRecorder, which produces container-encoded chunks:
final mimeType = web.MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
? 'audio/webm;codecs=opus'
: 'audio/webm';
final recorder = web.MediaRecorder(_mic!, web.MediaRecorderOptions(mimeType: mimeType));
final chunks = <web.BlobEvent>[];
recorder.addEventListener('dataavailable', (web.Event e) {
final data = (e as web.BlobEvent).data;
if (data.size > 0) chunks.add(e);
}.toJS);
recorder.start();
// on stop: final bytes = await blob.arrayBuffer().toDart; // -> Uint8List
The precise route is the Web Audio API: create an AudioContext, call createMediaStreamSource(stream), and pull PCM frames into Dart through an audio worklet. For speech-to-text, you usually want raw PCM (16 kHz mono is a common STT contract), which is exactly what record’s stream mode provides - see the next section.
Safari, iOS, and home-screen quirks
Safari has several documented traps. An AudioContext starts in the suspended state unless it is created or resumed inside a user gesture, and on iOS the tap on “Allow” in the permission sheet does not count as that gesture - so chain the AudioContext work into the same synchronous tap handler that triggers getUserMedia, with no awaits in between. WebKit also suspends capture that is not feeding an active audio pipeline, so connect the stream to a running context immediately rather than holding it unattached. iOS Safari additionally allows only one capture stream at a time: cache and reuse _mic instead of re-requesting per utterance.
Home-screen PWAs are a separate story. getUserMedia in standalone web apps was broken for years (WebKit bug 185448) and works from iOS 13.4 onward, with MediaRecorder available since 14.5 and Web Speech recognition since 14.5 - so current iOS PWAs can capture audio, but test the installed app, not just Safari tabs.
Wrapping packages: record, flutter_sound, speech_to_text
You do not always need raw interop. record (7.1.2) is the strongest wrapper: it supports web alongside Android, iOS, Windows, macOS, and Linux, and its stream mode gives PCM straight to Dart:
final recorder = AudioRecorder();
if (await recorder.hasPermission()) {
final stream = await recorder.start(
const RecordConfig(encoder: AudioEncoder.pcm16bits, sampleRate: 16000),
);
// consume stream as an audio pipeline input
}
recorder.dispose();
Two caveats from its docs: the permission check is not supported on web (the browser prompt is the check), and file encoders on web are limited - wav and pcm16bits work everywhere, while others vary by browser. flutter_sound also plays on web, but its own guide warns that the recorder does not work on Safari or iOS browsers, and its web build needs no FFmpeg and honors CORS for remote playback - treat web recording there as unverified and test on device. speech_to_text (7.5.0) covers web through the browser’s Web Speech API: initialize() returns false when the browser is unsupported (Firefox and Brave are known gaps), listen(onResult: ...) streams partial results, and it works under Wasm builds - ideal when the browser’s recognizer is enough and you do not need your own audio pipeline.
Cleanup: stop every track
A live MediaStream keeps the browser’s recording indicator on and holds the hardware. Stop every track when the feature is not active:
Future<void> stopMic() async {
final stream = _mic;
if (stream == null) return;
for (final track in stream.getTracks().toDart) {
track.stop();
}
_mic = null;
}
Also stop your MediaRecorder, cancel event listeners you added (store the .toJS closure so removeEventListener gets the same reference), and close the AudioContext if you created one. On iOS, remember that ending a track while a pipeline still references it produces a silent, “recording stopped immediately” symptom - so stop tracks deliberately, in one place, when the user leaves the screen.
Takeaway: Serve over HTTPS, request the mic through package:web’s getUserMedia with .toJS/.toDart conversions, prefer ideal constraints plus echo cancellation, route PCM into STT with record’s stream mode (or skip straight to speech_to_text), and always stop every MediaStreamTrack so the browser’s recording indicator - and your user’s trust - goes away.
Sources
- https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
- https://pub.dev/documentation/web/latest/web/MediaDevices/getUserMedia.html
- https://pub.dev/packages/record
- https://pub.dev/packages/record_web
- https://pub.dev/packages/flutter_sound
- https://flutter-sound.canardoux.xyz/guides_web.html
- https://pub.dev/packages/speech_to_text
- https://firt.dev/notes/pwa-ios/