@independo/capacitor-voice-recorder 8.1.8 → 8.1.9-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -322,10 +322,11 @@ Interface representing a generic response with a boolean value.
322
322
 
323
323
  Can be used to specify options for the recording.
324
324
 
325
- | Prop | Type | Description |
326
- | ------------------ | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
327
- | **`directory`** | <code><a href="#directory">Directory</a></code> | The capacitor filesystem directory where the recording should be saved. If not specified, the recording will be stored in a base64 string and returned in the <a href="#recordingdata">`RecordingData`</a> object. |
328
- | **`subDirectory`** | <code>string</code> | An optional subdirectory in the specified directory where the recording should be saved. |
325
+ | Prop | Type | Description |
326
+ | ---------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
327
+ | **`directory`** | <code><a href="#directory">Directory</a></code> | The capacitor filesystem directory where the recording should be saved. If not specified, the recording will be stored in a base64 string and returned in the <a href="#recordingdata">`RecordingData`</a> object. |
328
+ | **`subDirectory`** | <code>string</code> | An optional subdirectory in the specified directory where the recording should be saved. |
329
+ | **`requirePlaybackSupport`** | <code>boolean</code> | Whether the web implementation should require the selected recording MIME type to also be playable by the browser's native HTML `&lt;audio&gt;` element. Defaults to `true` on web to reduce cases where `MediaRecorder` reports support for a format but the recorded file cannot be played back in the same browser (observed on some Safari/iOS/WKWebView combinations). Native platforms ignore this option. |
329
330
 
330
331
 
331
332
  #### RecordingData
package/dist/docs.json CHANGED
@@ -315,6 +315,13 @@
315
315
  "docs": "An optional subdirectory in the specified directory where the recording should be saved.",
316
316
  "complexTypes": [],
317
317
  "type": "string | undefined"
318
+ },
319
+ {
320
+ "name": "requirePlaybackSupport",
321
+ "tags": [],
322
+ "docs": "Whether the web implementation should require the selected recording MIME type\nto also be playable by the browser's native HTML `<audio>` element.\n\nDefaults to `true` on web to reduce cases where `MediaRecorder` reports support\nfor a format but the recorded file cannot be played back in the same browser\n(observed on some Safari/iOS/WKWebView combinations).\n\nNative platforms ignore this option.",
323
+ "complexTypes": [],
324
+ "type": "boolean | undefined"
318
325
  }
319
326
  ]
320
327
  },
@@ -19,6 +19,17 @@ export interface RecordingOptions {
19
19
  * An optional subdirectory in the specified directory where the recording should be saved.
20
20
  */
21
21
  subDirectory?: string;
22
+ /**
23
+ * Whether the web implementation should require the selected recording MIME type
24
+ * to also be playable by the browser's native HTML `<audio>` element.
25
+ *
26
+ * Defaults to `true` on web to reduce cases where `MediaRecorder` reports support
27
+ * for a format but the recorded file cannot be played back in the same browser
28
+ * (observed on some Safari/iOS/WKWebView combinations).
29
+ *
30
+ * Native platforms ignore this option.
31
+ */
32
+ requirePlaybackSupport?: boolean;
22
33
  }
23
34
  /**
24
35
  * Interface representing the data of a recording.
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type {PluginListenerHandle} from \"@capacitor/core\";\nimport type {Directory} from \"@capacitor/filesystem\";\n\n/**\n * Represents a Base64 encoded string.\n */\nexport type Base64String = string;\n\n/**\n * Can be used to specify options for the recording.\n */\nexport interface RecordingOptions {\n /**\n * The capacitor filesystem directory where the recording should be saved.\n *\n * If not specified, the recording will be stored in a base64 string and returned in the `RecordingData` object.\n * @see RecordingData\n */\n directory?: Directory;\n\n /**\n * An optional subdirectory in the specified directory where the recording should be saved.\n */\n subDirectory?: string;\n}\n\n/**\n * Interface representing the data of a recording.\n */\nexport interface RecordingData {\n /**\n * The value containing the recording details.\n */\n value: {\n /**\n * The recorded data as a Base64 encoded string.\n */\n recordDataBase64: Base64String;\n /**\n * The duration of the recording in milliseconds.\n */\n msDuration: number;\n /**\n * The MIME type of the recorded file.\n */\n mimeType: string;\n\n /**\n * The URI of the recording file.\n */\n uri?: string;\n };\n}\n\n/**\n * Interface representing a generic response with a boolean value.\n */\nexport interface GenericResponse {\n /**\n * The result of the operation as a boolean value.\n */\n value: boolean;\n}\n\n/**\n * Interface representing the current status of the voice recorder.\n */\nexport interface CurrentRecordingStatus {\n /**\n * The current status of the recorder, which can be one of the following values: 'RECORDING', 'PAUSED', 'INTERRUPTED', 'NONE'.\n */\n status: 'RECORDING' | 'PAUSED' | 'INTERRUPTED' | 'NONE';\n}\n\n/**\n * Event payload for voiceRecordingInterrupted event (empty - no data).\n */\nexport type VoiceRecordingInterruptedEvent = Record<string, never>;\n\n/**\n * Event payload for voiceRecordingInterruptionEnded event (empty - no data).\n */\nexport type VoiceRecordingInterruptionEndedEvent = Record<string, never>;\n\n/**\n * Interface for the VoiceRecorderPlugin which provides methods to record audio.\n */\nexport interface VoiceRecorderPlugin {\n /**\n * Checks if the current device can record audio.\n * On mobile, this function will always resolve to `{ value: true }`.\n * In a browser, it will resolve to `{ value: true }` or `{ value: false }` based on the browser's ability to record.\n * This method does not take into account the permission status, only if the browser itself is capable of recording at all.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with code \"COULD_NOT_QUERY_PERMISSION_STATUS\" if the device cannot query the permission status.\n */\n canDeviceVoiceRecord(): Promise<GenericResponse>;\n\n /**\n * Requests audio recording permission from the user.\n * If the permission has already been provided, the promise will resolve with `{ value: true }`.\n * Otherwise, the promise will resolve to `{ value: true }` or `{ value: false }` based on the user's response.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error if the permission request fails.\n */\n requestAudioRecordingPermission(): Promise<GenericResponse>;\n\n /**\n * Checks if audio recording permission has been granted.\n * Will resolve to `{ value: true }` or `{ value: false }` based on the status of the permission.\n * The web implementation of this plugin uses the Permissions API, which is not widespread.\n * If the status of the permission cannot be checked, the promise will reject with `COULD_NOT_QUERY_PERMISSION_STATUS`.\n * In that case, use `requestAudioRecordingPermission` or `startRecording` and capture any exception that is thrown.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with code \"COULD_NOT_QUERY_PERMISSION_STATUS\" if the device cannot query the permission status.\n */\n hasAudioRecordingPermission(): Promise<GenericResponse>;\n\n /**\n * Starts audio recording.\n * On success, the promise will resolve to { value: true }.\n * On error, the promise will reject with one of the following error codes:\n * \"MISSING_PERMISSION\", \"ALREADY_RECORDING\", \"MICROPHONE_BEING_USED\", \"DEVICE_CANNOT_VOICE_RECORD\", or \"FAILED_TO_RECORD\".\n * @param options The options for the recording.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be started.\n */\n startRecording(options?: RecordingOptions): Promise<GenericResponse>;\n\n /**\n * Stops audio recording.\n * Will stop the recording that has been previously started.\n * If the function `startRecording` has not been called beforehand, the promise will reject with `RECORDING_HAS_NOT_STARTED`.\n * If the recording has been stopped immediately after it has been started, the promise will reject with `EMPTY_RECORDING`.\n * In a case of unknown error, the promise will reject with `FAILED_TO_FETCH_RECORDING`.\n * On iOS, if a recording interrupted by the system cannot be merged, the promise will reject with `FAILED_TO_MERGE_RECORDING`.\n * In case of success, the promise resolves to RecordingData containing the recording in base-64, the duration of the recording in milliseconds, and the MIME type.\n * @returns A promise that resolves to RecordingData.\n * @throws Error with one of the specified error codes if the recording cannot be stopped.\n */\n stopRecording(): Promise<RecordingData>;\n\n /**\n * Pauses the ongoing audio recording.\n * If the recording has not started yet, the promise will reject with an error code `RECORDING_HAS_NOT_STARTED`.\n * On success, the promise will resolve to { value: true } if the pause was successful or { value: false } if the recording is already paused.\n * On certain mobile OS versions, this function is not supported and will reject with `NOT_SUPPORTED_OS_VERSION`.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be paused.\n */\n pauseRecording(): Promise<GenericResponse>;\n\n /**\n * Resumes a paused or interrupted audio recording.\n * If the recording has not started yet, the promise will reject with an error code `RECORDING_HAS_NOT_STARTED`.\n * On success, the promise will resolve to { value: true } if the resume was successful or { value: false } if the recording is already running.\n * On certain mobile OS versions, this function is not supported and will reject with `NOT_SUPPORTED_OS_VERSION`.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be resumed.\n */\n resumeRecording(): Promise<GenericResponse>;\n\n /**\n * Gets the current status of the voice recorder.\n * Will resolve with one of the following values:\n * `{ status: \"NONE\" }` if the plugin is idle and waiting to start a new recording.\n * `{ status: \"RECORDING\" }` if the plugin is in the middle of recording.\n * `{ status: \"PAUSED\" }` if the recording is paused.\n * `{ status: \"INTERRUPTED\" }` if the recording was paused due to a system interruption.\n * @returns A promise that resolves to a CurrentRecordingStatus.\n * @throws Error if the status cannot be fetched.\n */\n getCurrentStatus(): Promise<CurrentRecordingStatus>;\n\n /**\n * Listen for audio recording interruptions (e.g., phone calls, other apps using microphone).\n * Available on iOS and Android only.\n *\n * @param eventName The name of the event to listen for.\n * @param listenerFunc The callback function to invoke when the event occurs.\n * @returns A promise that resolves to a PluginListenerHandle.\n */\n addListener(\n eventName: 'voiceRecordingInterrupted',\n listenerFunc: (event: VoiceRecordingInterruptedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /**\n * Listen for audio recording interruption end events.\n * Available on iOS and Android only.\n *\n * @param eventName The name of the event to listen for.\n * @param listenerFunc The callback function to invoke when the event occurs.\n * @returns A promise that resolves to a PluginListenerHandle.\n */\n addListener(\n eventName: 'voiceRecordingInterruptionEnded',\n listenerFunc: (event: VoiceRecordingInterruptionEndedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /**\n * Remove all listeners for this plugin.\n */\n removeAllListeners(): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"","sourcesContent":["import type {PluginListenerHandle} from \"@capacitor/core\";\nimport type {Directory} from \"@capacitor/filesystem\";\n\n/**\n * Represents a Base64 encoded string.\n */\nexport type Base64String = string;\n\n/**\n * Can be used to specify options for the recording.\n */\nexport interface RecordingOptions {\n /**\n * The capacitor filesystem directory where the recording should be saved.\n *\n * If not specified, the recording will be stored in a base64 string and returned in the `RecordingData` object.\n * @see RecordingData\n */\n directory?: Directory;\n\n /**\n * An optional subdirectory in the specified directory where the recording should be saved.\n */\n subDirectory?: string;\n\n /**\n * Whether the web implementation should require the selected recording MIME type\n * to also be playable by the browser's native HTML `<audio>` element.\n *\n * Defaults to `true` on web to reduce cases where `MediaRecorder` reports support\n * for a format but the recorded file cannot be played back in the same browser\n * (observed on some Safari/iOS/WKWebView combinations).\n *\n * Native platforms ignore this option.\n */\n requirePlaybackSupport?: boolean;\n}\n\n/**\n * Interface representing the data of a recording.\n */\nexport interface RecordingData {\n /**\n * The value containing the recording details.\n */\n value: {\n /**\n * The recorded data as a Base64 encoded string.\n */\n recordDataBase64: Base64String;\n /**\n * The duration of the recording in milliseconds.\n */\n msDuration: number;\n /**\n * The MIME type of the recorded file.\n */\n mimeType: string;\n\n /**\n * The URI of the recording file.\n */\n uri?: string;\n };\n}\n\n/**\n * Interface representing a generic response with a boolean value.\n */\nexport interface GenericResponse {\n /**\n * The result of the operation as a boolean value.\n */\n value: boolean;\n}\n\n/**\n * Interface representing the current status of the voice recorder.\n */\nexport interface CurrentRecordingStatus {\n /**\n * The current status of the recorder, which can be one of the following values: 'RECORDING', 'PAUSED', 'INTERRUPTED', 'NONE'.\n */\n status: 'RECORDING' | 'PAUSED' | 'INTERRUPTED' | 'NONE';\n}\n\n/**\n * Event payload for voiceRecordingInterrupted event (empty - no data).\n */\nexport type VoiceRecordingInterruptedEvent = Record<string, never>;\n\n/**\n * Event payload for voiceRecordingInterruptionEnded event (empty - no data).\n */\nexport type VoiceRecordingInterruptionEndedEvent = Record<string, never>;\n\n/**\n * Interface for the VoiceRecorderPlugin which provides methods to record audio.\n */\nexport interface VoiceRecorderPlugin {\n /**\n * Checks if the current device can record audio.\n * On mobile, this function will always resolve to `{ value: true }`.\n * In a browser, it will resolve to `{ value: true }` or `{ value: false }` based on the browser's ability to record.\n * This method does not take into account the permission status, only if the browser itself is capable of recording at all.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with code \"COULD_NOT_QUERY_PERMISSION_STATUS\" if the device cannot query the permission status.\n */\n canDeviceVoiceRecord(): Promise<GenericResponse>;\n\n /**\n * Requests audio recording permission from the user.\n * If the permission has already been provided, the promise will resolve with `{ value: true }`.\n * Otherwise, the promise will resolve to `{ value: true }` or `{ value: false }` based on the user's response.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error if the permission request fails.\n */\n requestAudioRecordingPermission(): Promise<GenericResponse>;\n\n /**\n * Checks if audio recording permission has been granted.\n * Will resolve to `{ value: true }` or `{ value: false }` based on the status of the permission.\n * The web implementation of this plugin uses the Permissions API, which is not widespread.\n * If the status of the permission cannot be checked, the promise will reject with `COULD_NOT_QUERY_PERMISSION_STATUS`.\n * In that case, use `requestAudioRecordingPermission` or `startRecording` and capture any exception that is thrown.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with code \"COULD_NOT_QUERY_PERMISSION_STATUS\" if the device cannot query the permission status.\n */\n hasAudioRecordingPermission(): Promise<GenericResponse>;\n\n /**\n * Starts audio recording.\n * On success, the promise will resolve to { value: true }.\n * On error, the promise will reject with one of the following error codes:\n * \"MISSING_PERMISSION\", \"ALREADY_RECORDING\", \"MICROPHONE_BEING_USED\", \"DEVICE_CANNOT_VOICE_RECORD\", or \"FAILED_TO_RECORD\".\n * @param options The options for the recording.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be started.\n */\n startRecording(options?: RecordingOptions): Promise<GenericResponse>;\n\n /**\n * Stops audio recording.\n * Will stop the recording that has been previously started.\n * If the function `startRecording` has not been called beforehand, the promise will reject with `RECORDING_HAS_NOT_STARTED`.\n * If the recording has been stopped immediately after it has been started, the promise will reject with `EMPTY_RECORDING`.\n * In a case of unknown error, the promise will reject with `FAILED_TO_FETCH_RECORDING`.\n * On iOS, if a recording interrupted by the system cannot be merged, the promise will reject with `FAILED_TO_MERGE_RECORDING`.\n * In case of success, the promise resolves to RecordingData containing the recording in base-64, the duration of the recording in milliseconds, and the MIME type.\n * @returns A promise that resolves to RecordingData.\n * @throws Error with one of the specified error codes if the recording cannot be stopped.\n */\n stopRecording(): Promise<RecordingData>;\n\n /**\n * Pauses the ongoing audio recording.\n * If the recording has not started yet, the promise will reject with an error code `RECORDING_HAS_NOT_STARTED`.\n * On success, the promise will resolve to { value: true } if the pause was successful or { value: false } if the recording is already paused.\n * On certain mobile OS versions, this function is not supported and will reject with `NOT_SUPPORTED_OS_VERSION`.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be paused.\n */\n pauseRecording(): Promise<GenericResponse>;\n\n /**\n * Resumes a paused or interrupted audio recording.\n * If the recording has not started yet, the promise will reject with an error code `RECORDING_HAS_NOT_STARTED`.\n * On success, the promise will resolve to { value: true } if the resume was successful or { value: false } if the recording is already running.\n * On certain mobile OS versions, this function is not supported and will reject with `NOT_SUPPORTED_OS_VERSION`.\n * @returns A promise that resolves to a GenericResponse.\n * @throws Error with one of the specified error codes if the recording cannot be resumed.\n */\n resumeRecording(): Promise<GenericResponse>;\n\n /**\n * Gets the current status of the voice recorder.\n * Will resolve with one of the following values:\n * `{ status: \"NONE\" }` if the plugin is idle and waiting to start a new recording.\n * `{ status: \"RECORDING\" }` if the plugin is in the middle of recording.\n * `{ status: \"PAUSED\" }` if the recording is paused.\n * `{ status: \"INTERRUPTED\" }` if the recording was paused due to a system interruption.\n * @returns A promise that resolves to a CurrentRecordingStatus.\n * @throws Error if the status cannot be fetched.\n */\n getCurrentStatus(): Promise<CurrentRecordingStatus>;\n\n /**\n * Listen for audio recording interruptions (e.g., phone calls, other apps using microphone).\n * Available on iOS and Android only.\n *\n * @param eventName The name of the event to listen for.\n * @param listenerFunc The callback function to invoke when the event occurs.\n * @returns A promise that resolves to a PluginListenerHandle.\n */\n addListener(\n eventName: 'voiceRecordingInterrupted',\n listenerFunc: (event: VoiceRecordingInterruptedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /**\n * Listen for audio recording interruption end events.\n * Available on iOS and Android only.\n *\n * @param eventName The name of the event to listen for.\n * @param listenerFunc The callback function to invoke when the event occurs.\n * @returns A promise that resolves to a PluginListenerHandle.\n */\n addListener(\n eventName: 'voiceRecordingInterruptionEnded',\n listenerFunc: (event: VoiceRecordingInterruptionEndedEvent) => void,\n ): Promise<PluginListenerHandle>;\n\n /**\n * Remove all listeners for this plugin.\n */\n removeAllListeners(): Promise<void>;\n}\n"]}
@@ -1,23 +1,66 @@
1
1
  import type { CurrentRecordingStatus, GenericResponse, RecordingData, RecordingOptions } from '../../definitions';
2
- /** Preferred MIME types to probe in order of fallback. */
3
- declare const POSSIBLE_MIME_TYPES: {
4
- 'audio/aac': string;
5
- 'audio/webm;codecs=opus': string;
6
- 'audio/mp4': string;
7
- 'audio/webm': string;
8
- 'audio/ogg;codecs=opus': string;
9
- };
2
+ /**
3
+ * Ordered MIME types to probe for audio recording via `MediaRecorder.isTypeSupported()`.
4
+ *
5
+ * ⚠️ The order is intentional and MUST remain stable unless you also update the
6
+ * selection policy in code and test on Safari/iOS + WebViews.
7
+ *
8
+ * ✅ What this list is used for
9
+ * - Selecting a `mimeType` for `new MediaRecorder(stream, { mimeType })`.
10
+ *
11
+ * ❌ What this list does NOT guarantee
12
+ * - It does NOT guarantee that the recorded output will be playable via the
13
+ * HTML `<audio>` element in the same browser.
14
+ *
15
+ * Real-world caveat (important):
16
+ * - We have observed cases where `MediaRecorder.isTypeSupported('audio/webm;codecs=opus')`
17
+ * returned `true`, the recorder produced a Blob, but `<audio>` could not play it.
18
+ * This can happen due to container/codec playback support differences, platform
19
+ * quirks (especially Safari/iOS / WKWebView), or incomplete WebM playback support.
20
+ *
21
+ * Current selection behavior in this implementation:
22
+ * - By default, MIME selection treats recorder support and playback support as separate
23
+ * capabilities and probes both:
24
+ * - Recorder capability: `MediaRecorder.isTypeSupported(type)`
25
+ * - Playback capability: `audio.canPlayType(type)`
26
+ * - This default can be disabled via `RecordingOptions.requirePlaybackSupport = false`
27
+ * to fall back to recorder-only probing.
28
+ *
29
+ * Keeping legacy keys:
30
+ * - Some entries are kept even if they overlap (e.g. `audio/mp4` and explicit codec),
31
+ * to maximize compatibility across differing browser implementations.
32
+ */
33
+ declare const POSSIBLE_MIME_TYPES: Record<string, string>;
10
34
  /** Browser implementation backed by MediaRecorder and Capacitor Filesystem. */
11
35
  export declare class VoiceRecorderImpl {
36
+ /** Default behavior for web MIME selection: require recorder + playback support. */
37
+ private static readonly DEFAULT_REQUIRE_PLAYBACK_SUPPORT;
12
38
  /** Active MediaRecorder instance, if recording. */
13
39
  private mediaRecorder;
40
+ /** MIME type selected at start time for the active recording. */
41
+ private activeMimeType;
14
42
  /** Collected data chunks from MediaRecorder. */
15
43
  private chunks;
16
44
  /** Promise resolved when the recorder stops and payload is ready. */
17
45
  private pendingResult;
18
- /** Returns whether the browser can start a recording session. */
19
- static canDeviceVoiceRecord(): Promise<GenericResponse>;
20
- /** Starts a recording session using MediaRecorder. */
46
+ /**
47
+ * Returns whether the browser can start a recording session.
48
+ *
49
+ * On web this checks:
50
+ * - `navigator.mediaDevices.getUserMedia`
51
+ * - at least one supported recording MIME type using {@link getSupportedMimeType}
52
+ *
53
+ * The optional `requirePlaybackSupport` flag is forwarded to MIME selection and defaults
54
+ * to `true` when omitted.
55
+ */
56
+ static canDeviceVoiceRecord(options?: Pick<RecordingOptions, 'requirePlaybackSupport'>): Promise<GenericResponse>;
57
+ /**
58
+ * Starts a recording session using `MediaRecorder`.
59
+ *
60
+ * The selected MIME type is resolved once at start time (using the optional
61
+ * `requirePlaybackSupport` flag from `RecordingOptions`) and reused for the final Blob
62
+ * and file extension to keep the recording payload internally consistent.
63
+ */
21
64
  startRecording(options?: RecordingOptions): Promise<GenericResponse>;
22
65
  /** Stops the current recording and resolves the pending payload. */
23
66
  stopRecording(): Promise<RecordingData>;
@@ -31,8 +74,41 @@ export declare class VoiceRecorderImpl {
31
74
  resumeRecording(): Promise<GenericResponse>;
32
75
  /** Returns the current recording status from MediaRecorder. */
33
76
  getCurrentStatus(): Promise<CurrentRecordingStatus>;
34
- /** Returns the first supported MIME type, if any. */
35
- static getSupportedMimeType<T extends keyof typeof POSSIBLE_MIME_TYPES>(): T | null;
77
+ /**
78
+ * Returns the first MIME type (key of {@link POSSIBLE_MIME_TYPES}) that the current
79
+ * environment reports as supported for recording via `MediaRecorder.isTypeSupported()`,
80
+ * optionally requiring native HTML `<audio>` playback support too.
81
+ *
82
+ * The search order is the iteration order of {@link POSSIBLE_MIME_TYPES}.
83
+ *
84
+ * @typeParam T - A MIME type string that exists as a key in {@link POSSIBLE_MIME_TYPES}.
85
+ *
86
+ * @returns The first supported MIME type for `MediaRecorder`, or `null` if:
87
+ * - `MediaRecorder` is unavailable, or
88
+ * - no configured MIME types are supported.
89
+ *
90
+ * ⚠️ Important: `MediaRecorder` support ≠ `<audio>` playback support
91
+ *
92
+ * Some browsers/platforms can claim support for recording a format (notably WebM/Opus)
93
+ * but still fail to play the resulting Blob through the native HTML audio pipeline.
94
+ * This mismatch is especially likely on Safari/iOS / WKWebView variants, so the default
95
+ * behavior also probes `HTMLAudioElement.canPlayType(type)` when available.
96
+ *
97
+ * Selection policy when playback probing is enabled:
98
+ * - keep the global priority order from {@link POSSIBLE_MIME_TYPES}
99
+ * - among recordable types, prefer the first `"probably"` playable candidate
100
+ * - otherwise return the first `"maybe"` playable candidate
101
+ * - treat `""` as not playable
102
+ *
103
+ * Note: The <audio> element is never attached to the DOM, so it won't appear to users or assistive tech.
104
+ *
105
+ * Fallback behavior:
106
+ * - If `document` / `audio.canPlayType` is unavailable (e.g. SSR-like environments),
107
+ * this falls back to record-only probing.
108
+ */
109
+ static getSupportedMimeType<T extends keyof typeof POSSIBLE_MIME_TYPES>(options?: {
110
+ requirePlaybackSupport?: boolean;
111
+ }): T | null;
36
112
  /** Initializes MediaRecorder and wires up handlers. */
37
113
  private onSuccessfullyStartedRecording;
38
114
  /** Handles failures from getUserMedia. */
@@ -2,13 +2,51 @@ import { Filesystem } from '@capacitor/filesystem';
2
2
  import write_blob from 'capacitor-blob-writer';
3
3
  import getBlobDuration from './get-blob-duration';
4
4
  import { alreadyRecordingError, couldNotQueryPermissionStatusError, deviceCannotVoiceRecordError, emptyRecordingError, failedToFetchRecordingError, failedToRecordError, failureResponse, missingPermissionError, recordingHasNotStartedError, successResponse, } from './predefined-web-responses';
5
- /** Preferred MIME types to probe in order of fallback. */
5
+ /**
6
+ * Ordered MIME types to probe for audio recording via `MediaRecorder.isTypeSupported()`.
7
+ *
8
+ * ⚠️ The order is intentional and MUST remain stable unless you also update the
9
+ * selection policy in code and test on Safari/iOS + WebViews.
10
+ *
11
+ * ✅ What this list is used for
12
+ * - Selecting a `mimeType` for `new MediaRecorder(stream, { mimeType })`.
13
+ *
14
+ * ❌ What this list does NOT guarantee
15
+ * - It does NOT guarantee that the recorded output will be playable via the
16
+ * HTML `<audio>` element in the same browser.
17
+ *
18
+ * Real-world caveat (important):
19
+ * - We have observed cases where `MediaRecorder.isTypeSupported('audio/webm;codecs=opus')`
20
+ * returned `true`, the recorder produced a Blob, but `<audio>` could not play it.
21
+ * This can happen due to container/codec playback support differences, platform
22
+ * quirks (especially Safari/iOS / WKWebView), or incomplete WebM playback support.
23
+ *
24
+ * Current selection behavior in this implementation:
25
+ * - By default, MIME selection treats recorder support and playback support as separate
26
+ * capabilities and probes both:
27
+ * - Recorder capability: `MediaRecorder.isTypeSupported(type)`
28
+ * - Playback capability: `audio.canPlayType(type)`
29
+ * - This default can be disabled via `RecordingOptions.requirePlaybackSupport = false`
30
+ * to fall back to recorder-only probing.
31
+ *
32
+ * Keeping legacy keys:
33
+ * - Some entries are kept even if they overlap (e.g. `audio/mp4` and explicit codec),
34
+ * to maximize compatibility across differing browser implementations.
35
+ */
6
36
  const POSSIBLE_MIME_TYPES = {
7
- 'audio/aac': '.aac',
8
- 'audio/webm;codecs=opus': '.ogg',
9
- 'audio/mp4': '.mp3',
10
- 'audio/webm': '.ogg',
11
- 'audio/ogg;codecs=opus': '.ogg',
37
+ // ✅ Most universal
38
+ 'audio/mp4;codecs="mp4a.40.2"': '.m4a', // AAC in MP4 (explicit codec helps detection)
39
+ 'audio/mp4': '.m4a', // (legacy key kept; broad support)
40
+ 'audio/aac': '.aac', // (legacy key kept; less common in the wild)
41
+ 'audio/mpeg': '.mp3', // MP3 (universal)
42
+ 'audio/wav': '.wav', // WAV (universal, big files)
43
+ // ✅ Modern high-quality (very widely supported, but slightly less “universal” than MP3/AAC)
44
+ 'audio/webm;codecs="opus"': '.webm', // Opus in WebM (explicit codec helps detection)
45
+ 'audio/webm;codecs=opus': '.webm', // (legacy key kept)
46
+ 'audio/webm': '.webm', // (legacy key kept; container-only, codec-dependent)
47
+ // ⚠️ Least universal (Safari/iOS historically the limiting factor)
48
+ 'audio/ogg;codecs=opus': '.ogg', // (legacy key kept)
49
+ 'audio/ogg;codecs=vorbis': '.ogg', // Ogg Vorbis (weakest mainstream support)
12
50
  };
13
51
  /** Creates a promise that never resolves. */
14
52
  const neverResolvingPromise = () => new Promise(() => undefined);
@@ -17,27 +55,47 @@ export class VoiceRecorderImpl {
17
55
  constructor() {
18
56
  /** Active MediaRecorder instance, if recording. */
19
57
  this.mediaRecorder = null;
58
+ /** MIME type selected at start time for the active recording. */
59
+ this.activeMimeType = null;
20
60
  /** Collected data chunks from MediaRecorder. */
21
61
  this.chunks = [];
22
62
  /** Promise resolved when the recorder stops and payload is ready. */
23
63
  this.pendingResult = neverResolvingPromise();
24
64
  }
25
- /** Returns whether the browser can start a recording session. */
26
- static async canDeviceVoiceRecord() {
65
+ /**
66
+ * Returns whether the browser can start a recording session.
67
+ *
68
+ * On web this checks:
69
+ * - `navigator.mediaDevices.getUserMedia`
70
+ * - at least one supported recording MIME type using {@link getSupportedMimeType}
71
+ *
72
+ * The optional `requirePlaybackSupport` flag is forwarded to MIME selection and defaults
73
+ * to `true` when omitted.
74
+ */
75
+ static async canDeviceVoiceRecord(options) {
27
76
  var _a;
28
- if (((_a = navigator === null || navigator === void 0 ? void 0 : navigator.mediaDevices) === null || _a === void 0 ? void 0 : _a.getUserMedia) == null || VoiceRecorderImpl.getSupportedMimeType() == null) {
77
+ if (((_a = navigator === null || navigator === void 0 ? void 0 : navigator.mediaDevices) === null || _a === void 0 ? void 0 : _a.getUserMedia) == null ||
78
+ VoiceRecorderImpl.getSupportedMimeType({
79
+ requirePlaybackSupport: options === null || options === void 0 ? void 0 : options.requirePlaybackSupport,
80
+ }) == null) {
29
81
  return failureResponse();
30
82
  }
31
83
  else {
32
84
  return successResponse();
33
85
  }
34
86
  }
35
- /** Starts a recording session using MediaRecorder. */
87
+ /**
88
+ * Starts a recording session using `MediaRecorder`.
89
+ *
90
+ * The selected MIME type is resolved once at start time (using the optional
91
+ * `requirePlaybackSupport` flag from `RecordingOptions`) and reused for the final Blob
92
+ * and file extension to keep the recording payload internally consistent.
93
+ */
36
94
  async startRecording(options) {
37
95
  if (this.mediaRecorder != null) {
38
96
  throw alreadyRecordingError();
39
97
  }
40
- const deviceCanRecord = await VoiceRecorderImpl.canDeviceVoiceRecord();
98
+ const deviceCanRecord = await VoiceRecorderImpl.canDeviceVoiceRecord(options);
41
99
  if (!deviceCanRecord.value) {
42
100
  throw deviceCannotVoiceRecordError();
43
101
  }
@@ -139,30 +197,97 @@ export class VoiceRecorderImpl {
139
197
  return Promise.resolve({ status: 'NONE' });
140
198
  }
141
199
  }
142
- /** Returns the first supported MIME type, if any. */
143
- static getSupportedMimeType() {
200
+ /**
201
+ * Returns the first MIME type (key of {@link POSSIBLE_MIME_TYPES}) that the current
202
+ * environment reports as supported for recording via `MediaRecorder.isTypeSupported()`,
203
+ * optionally requiring native HTML `<audio>` playback support too.
204
+ *
205
+ * The search order is the iteration order of {@link POSSIBLE_MIME_TYPES}.
206
+ *
207
+ * @typeParam T - A MIME type string that exists as a key in {@link POSSIBLE_MIME_TYPES}.
208
+ *
209
+ * @returns The first supported MIME type for `MediaRecorder`, or `null` if:
210
+ * - `MediaRecorder` is unavailable, or
211
+ * - no configured MIME types are supported.
212
+ *
213
+ * ⚠️ Important: `MediaRecorder` support ≠ `<audio>` playback support
214
+ *
215
+ * Some browsers/platforms can claim support for recording a format (notably WebM/Opus)
216
+ * but still fail to play the resulting Blob through the native HTML audio pipeline.
217
+ * This mismatch is especially likely on Safari/iOS / WKWebView variants, so the default
218
+ * behavior also probes `HTMLAudioElement.canPlayType(type)` when available.
219
+ *
220
+ * Selection policy when playback probing is enabled:
221
+ * - keep the global priority order from {@link POSSIBLE_MIME_TYPES}
222
+ * - among recordable types, prefer the first `"probably"` playable candidate
223
+ * - otherwise return the first `"maybe"` playable candidate
224
+ * - treat `""` as not playable
225
+ *
226
+ * Note: The <audio> element is never attached to the DOM, so it won't appear to users or assistive tech.
227
+ *
228
+ * Fallback behavior:
229
+ * - If `document` / `audio.canPlayType` is unavailable (e.g. SSR-like environments),
230
+ * this falls back to record-only probing.
231
+ */
232
+ static getSupportedMimeType(options) {
233
+ var _a, _b, _c, _d, _e;
144
234
  if ((MediaRecorder === null || MediaRecorder === void 0 ? void 0 : MediaRecorder.isTypeSupported) == null)
145
235
  return null;
146
- const foundSupportedType = Object.keys(POSSIBLE_MIME_TYPES).find((type) => MediaRecorder.isTypeSupported(type));
147
- return foundSupportedType !== null && foundSupportedType !== void 0 ? foundSupportedType : null;
236
+ const orderedTypes = Object.keys(POSSIBLE_MIME_TYPES);
237
+ const recordSupportedTypes = orderedTypes.filter((type) => MediaRecorder.isTypeSupported(type));
238
+ if (recordSupportedTypes.length === 0)
239
+ return null;
240
+ const requirePlaybackSupport = (_a = options === null || options === void 0 ? void 0 : options.requirePlaybackSupport) !== null && _a !== void 0 ? _a : VoiceRecorderImpl.DEFAULT_REQUIRE_PLAYBACK_SUPPORT;
241
+ if (!requirePlaybackSupport) {
242
+ return (_b = recordSupportedTypes[0]) !== null && _b !== void 0 ? _b : null;
243
+ }
244
+ if (typeof document === 'undefined' || typeof document.createElement !== 'function') {
245
+ return (_c = recordSupportedTypes[0]) !== null && _c !== void 0 ? _c : null;
246
+ }
247
+ const audioElement = document.createElement('audio');
248
+ if (typeof audioElement.canPlayType !== 'function') {
249
+ return (_d = recordSupportedTypes[0]) !== null && _d !== void 0 ? _d : null;
250
+ }
251
+ let firstProbably = null;
252
+ let firstMaybe = null;
253
+ for (const type of recordSupportedTypes) {
254
+ const playbackSupport = audioElement.canPlayType(type);
255
+ if (playbackSupport === 'probably') {
256
+ firstProbably = type;
257
+ break;
258
+ }
259
+ if (playbackSupport === 'maybe' && firstMaybe == null) {
260
+ firstMaybe = type;
261
+ }
262
+ }
263
+ return (_e = firstProbably !== null && firstProbably !== void 0 ? firstProbably : firstMaybe) !== null && _e !== void 0 ? _e : null;
148
264
  }
149
265
  /** Initializes MediaRecorder and wires up handlers. */
150
266
  onSuccessfullyStartedRecording(stream, options) {
151
267
  this.pendingResult = new Promise((resolve, reject) => {
152
- this.mediaRecorder = new MediaRecorder(stream);
268
+ const mimeType = VoiceRecorderImpl.getSupportedMimeType({
269
+ requirePlaybackSupport: options === null || options === void 0 ? void 0 : options.requirePlaybackSupport,
270
+ });
271
+ if (mimeType == null) {
272
+ this.prepareInstanceForNextOperation();
273
+ reject(failedToRecordError());
274
+ return;
275
+ }
276
+ this.activeMimeType = mimeType;
277
+ this.mediaRecorder = new MediaRecorder(stream, { mimeType });
153
278
  this.mediaRecorder.onerror = () => {
154
279
  this.prepareInstanceForNextOperation();
155
280
  reject(failedToRecordError());
156
281
  };
157
282
  this.mediaRecorder.onstop = async () => {
158
283
  var _a, _b, _c;
159
- const mimeType = VoiceRecorderImpl.getSupportedMimeType();
160
- if (mimeType == null) {
284
+ const finalMimeType = this.activeMimeType;
285
+ if (finalMimeType == null) {
161
286
  this.prepareInstanceForNextOperation();
162
287
  reject(failedToFetchRecordingError());
163
288
  return;
164
289
  }
165
- const blobVoiceRecording = new Blob(this.chunks, { type: mimeType });
290
+ const blobVoiceRecording = new Blob(this.chunks, { type: finalMimeType });
166
291
  if (blobVoiceRecording.size <= 0) {
167
292
  this.prepareInstanceForNextOperation();
168
293
  reject(emptyRecordingError());
@@ -172,7 +297,7 @@ export class VoiceRecorderImpl {
172
297
  let recordDataBase64 = '';
173
298
  if (options === null || options === void 0 ? void 0 : options.directory) {
174
299
  const subDirectory = (_c = (_b = (_a = options.subDirectory) === null || _a === void 0 ? void 0 : _a.match(/^\/?(.+[^/])\/?$/)) === null || _b === void 0 ? void 0 : _b[1]) !== null && _c !== void 0 ? _c : '';
175
- const path = `${subDirectory}/recording-${new Date().getTime()}${POSSIBLE_MIME_TYPES[mimeType]}`;
300
+ const path = `${subDirectory}/recording-${new Date().getTime()}${POSSIBLE_MIME_TYPES[finalMimeType]}`;
176
301
  await write_blob({
177
302
  blob: blobVoiceRecording,
178
303
  directory: options.directory,
@@ -187,7 +312,14 @@ export class VoiceRecorderImpl {
187
312
  }
188
313
  const recordingDuration = await getBlobDuration(blobVoiceRecording);
189
314
  this.prepareInstanceForNextOperation();
190
- resolve({ value: { recordDataBase64, mimeType, msDuration: recordingDuration * 1000, uri } });
315
+ resolve({
316
+ value: {
317
+ recordDataBase64,
318
+ mimeType: finalMimeType,
319
+ msDuration: recordingDuration * 1000,
320
+ uri
321
+ }
322
+ });
191
323
  };
192
324
  this.mediaRecorder.ondataavailable = (event) => this.chunks.push(event.data);
193
325
  this.mediaRecorder.start();
@@ -224,7 +356,10 @@ export class VoiceRecorderImpl {
224
356
  }
225
357
  this.pendingResult = neverResolvingPromise();
226
358
  this.mediaRecorder = null;
359
+ this.activeMimeType = null;
227
360
  this.chunks = [];
228
361
  }
229
362
  }
363
+ /** Default behavior for web MIME selection: require recorder + playback support. */
364
+ VoiceRecorderImpl.DEFAULT_REQUIRE_PLAYBACK_SUPPORT = true;
230
365
  //# sourceMappingURL=VoiceRecorderImpl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceRecorderImpl.js","sourceRoot":"","sources":["../../../../src/platform/web/VoiceRecorderImpl.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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EAAE,CAAC;YACzE,IAAI,CAAC;gBACD,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;YAC9B,CAAC;YAAC,OAAO,MAAM,EAAE,CAAC;gBACd,OAAO,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC;YAC5D,CAAC;QACL,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,qBAAqB,EAAE,CAAC;QAC7C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;IACrB,CAAC;CACJ","sourcesContent":["import {Filesystem} from '@capacitor/filesystem';\nimport write_blob from 'capacitor-blob-writer';\n\nimport type {\n Base64String,\n CurrentRecordingStatus,\n GenericResponse,\n RecordingData,\n RecordingOptions,\n} from '../../definitions';\n\nimport getBlobDuration from './get-blob-duration';\nimport {\n alreadyRecordingError,\n couldNotQueryPermissionStatusError,\n deviceCannotVoiceRecordError,\n emptyRecordingError,\n failedToFetchRecordingError,\n failedToRecordError,\n failureResponse,\n missingPermissionError,\n recordingHasNotStartedError,\n successResponse,\n} from './predefined-web-responses';\n\n/** Preferred MIME types to probe in order of fallback. */\nconst POSSIBLE_MIME_TYPES = {\n 'audio/aac': '.aac',\n 'audio/webm;codecs=opus': '.ogg',\n 'audio/mp4': '.mp3',\n 'audio/webm': '.ogg',\n 'audio/ogg;codecs=opus': '.ogg',\n};\n\n/** Creates a promise that never resolves. */\nconst neverResolvingPromise = (): Promise<any> => new Promise(() => undefined);\n\n/** Browser implementation backed by MediaRecorder and Capacitor Filesystem. */\nexport class VoiceRecorderImpl {\n /** Active MediaRecorder instance, if recording. */\n private mediaRecorder: MediaRecorder | null = null;\n /** Collected data chunks from MediaRecorder. */\n private chunks: any[] = [];\n /** Promise resolved when the recorder stops and payload is ready. */\n private pendingResult: Promise<RecordingData> = neverResolvingPromise();\n\n /** Returns whether the browser can start a recording session. */\n public static async canDeviceVoiceRecord(): Promise<GenericResponse> {\n if (navigator?.mediaDevices?.getUserMedia == null || VoiceRecorderImpl.getSupportedMimeType() == null) {\n return failureResponse();\n } else {\n return successResponse();\n }\n }\n\n /** Starts a recording session using MediaRecorder. */\n public async startRecording(options?: RecordingOptions): Promise<GenericResponse> {\n if (this.mediaRecorder != null) {\n throw alreadyRecordingError();\n }\n const deviceCanRecord = await VoiceRecorderImpl.canDeviceVoiceRecord();\n if (!deviceCanRecord.value) {\n throw deviceCannotVoiceRecordError();\n }\n const havingPermission = await VoiceRecorderImpl.hasAudioRecordingPermission().catch(() => successResponse());\n if (!havingPermission.value) {\n throw missingPermissionError();\n }\n\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then((stream) => this.onSuccessfullyStartedRecording(stream, options))\n .catch(this.onFailedToStartRecording.bind(this));\n }\n\n /** Stops the current recording and resolves the pending payload. */\n public async stopRecording(): Promise<RecordingData> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n }\n try {\n this.mediaRecorder.stop();\n this.mediaRecorder.stream.getTracks().forEach((track) => track.stop());\n return this.pendingResult;\n } catch (ignore) {\n throw failedToFetchRecordingError();\n } finally {\n this.prepareInstanceForNextOperation();\n }\n }\n\n /** Returns whether the browser has microphone permission. */\n public static async hasAudioRecordingPermission(): Promise<GenericResponse> {\n // Safari does not support navigator.permissions.query\n if (!navigator.permissions.query) {\n if (navigator.mediaDevices !== undefined) {\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then(() => successResponse())\n .catch(() => {\n throw couldNotQueryPermissionStatusError();\n });\n }\n }\n return navigator.permissions\n .query({name: 'microphone' as any})\n .then((result) => ({value: result.state === 'granted'}))\n .catch(() => {\n throw couldNotQueryPermissionStatusError();\n });\n }\n\n /** Requests microphone permission from the browser. */\n public static async requestAudioRecordingPermission(): Promise<GenericResponse> {\n const havingPermission = await VoiceRecorderImpl.hasAudioRecordingPermission().catch(() => failureResponse());\n if (havingPermission.value) {\n return successResponse();\n }\n\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then(() => successResponse())\n .catch(() => failureResponse());\n }\n\n /** Pauses the recording session when supported. */\n public pauseRecording(): Promise<GenericResponse> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n } else if (this.mediaRecorder.state === 'recording') {\n this.mediaRecorder.pause();\n return Promise.resolve(successResponse());\n } else {\n return Promise.resolve(failureResponse());\n }\n }\n\n /** Resumes a paused recording session when supported. */\n public resumeRecording(): Promise<GenericResponse> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n } else if (this.mediaRecorder.state === 'paused') {\n this.mediaRecorder.resume();\n return Promise.resolve(successResponse());\n } else {\n return Promise.resolve(failureResponse());\n }\n }\n\n /** Returns the current recording status from MediaRecorder. */\n public getCurrentStatus(): Promise<CurrentRecordingStatus> {\n if (this.mediaRecorder == null) {\n return Promise.resolve({status: 'NONE'});\n } else if (this.mediaRecorder.state === 'recording') {\n return Promise.resolve({status: 'RECORDING'});\n } else if (this.mediaRecorder.state === 'paused') {\n return Promise.resolve({status: 'PAUSED'});\n } else {\n return Promise.resolve({status: 'NONE'});\n }\n }\n\n /** Returns the first supported MIME type, if any. */\n public static getSupportedMimeType<T extends keyof typeof POSSIBLE_MIME_TYPES>(): T | null {\n if (MediaRecorder?.isTypeSupported == null) return null;\n\n const foundSupportedType = Object.keys(POSSIBLE_MIME_TYPES).find((type) => MediaRecorder.isTypeSupported(type)) as\n | T\n | undefined;\n\n return foundSupportedType ?? null;\n }\n\n /** Initializes MediaRecorder and wires up handlers. */\n private onSuccessfullyStartedRecording(stream: MediaStream, options?: RecordingOptions): GenericResponse {\n this.pendingResult = new Promise((resolve, reject) => {\n this.mediaRecorder = new MediaRecorder(stream);\n this.mediaRecorder.onerror = () => {\n this.prepareInstanceForNextOperation();\n reject(failedToRecordError());\n };\n this.mediaRecorder.onstop = async () => {\n const mimeType = VoiceRecorderImpl.getSupportedMimeType();\n if (mimeType == null) {\n this.prepareInstanceForNextOperation();\n reject(failedToFetchRecordingError());\n return;\n }\n const blobVoiceRecording = new Blob(this.chunks, {type: mimeType});\n if (blobVoiceRecording.size <= 0) {\n this.prepareInstanceForNextOperation();\n reject(emptyRecordingError());\n return;\n }\n\n let uri: string | undefined = undefined;\n let recordDataBase64 = '';\n if (options?.directory) {\n const subDirectory = options.subDirectory?.match(/^\\/?(.+[^/])\\/?$/)?.[1] ?? '';\n const path = `${subDirectory}/recording-${new Date().getTime()}${POSSIBLE_MIME_TYPES[mimeType]}`;\n\n await write_blob({\n blob: blobVoiceRecording,\n directory: options.directory,\n fast_mode: true,\n path,\n recursive: true,\n });\n\n ({uri} = await Filesystem.getUri({directory: options.directory, path}));\n } else {\n recordDataBase64 = await VoiceRecorderImpl.blobToBase64(blobVoiceRecording);\n }\n\n const recordingDuration = await getBlobDuration(blobVoiceRecording);\n this.prepareInstanceForNextOperation();\n resolve({value: {recordDataBase64, mimeType, msDuration: recordingDuration * 1000, uri}});\n };\n this.mediaRecorder.ondataavailable = (event: any) => this.chunks.push(event.data);\n this.mediaRecorder.start();\n });\n return successResponse();\n }\n\n /** Handles failures from getUserMedia. */\n private onFailedToStartRecording(): GenericResponse {\n this.prepareInstanceForNextOperation();\n throw failedToRecordError();\n }\n\n /** Converts a Blob payload into a base64 string. */\n private static blobToBase64(blob: Blob): Promise<Base64String> {\n return new Promise((resolve) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const recordingResult = String(reader.result);\n const splitResult = recordingResult.split('base64,');\n const toResolve = splitResult.length > 1 ? splitResult[1] : recordingResult;\n resolve(toResolve.trim());\n };\n reader.readAsDataURL(blob);\n });\n }\n\n /** Resets state for the next recording attempt. */\n private prepareInstanceForNextOperation(): void {\n if (this.mediaRecorder != null && this.mediaRecorder.state === 'recording') {\n try {\n this.mediaRecorder.stop();\n } catch (ignore) {\n console.warn('Failed to stop recording during cleanup');\n }\n }\n this.pendingResult = neverResolvingPromise();\n this.mediaRecorder = null;\n this.chunks = [];\n }\n}\n"]}
1
+ {"version":3,"file":"VoiceRecorderImpl.js","sourceRoot":"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,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;IACrB,CAAC;;AAnUD,oFAAoF;AAC5D,kDAAgC,GAAG,IAAI,AAAP,CAAQ","sourcesContent":["import {Filesystem} from '@capacitor/filesystem';\nimport write_blob from 'capacitor-blob-writer';\n\nimport type {\n Base64String,\n CurrentRecordingStatus,\n GenericResponse,\n RecordingData,\n RecordingOptions,\n} from '../../definitions';\n\nimport getBlobDuration from './get-blob-duration';\nimport {\n alreadyRecordingError,\n couldNotQueryPermissionStatusError,\n deviceCannotVoiceRecordError,\n emptyRecordingError,\n failedToFetchRecordingError,\n failedToRecordError,\n failureResponse,\n missingPermissionError,\n recordingHasNotStartedError,\n successResponse,\n} from './predefined-web-responses';\n\n/**\n * Ordered MIME types to probe for audio recording via `MediaRecorder.isTypeSupported()`.\n *\n * ⚠️ The order is intentional and MUST remain stable unless you also update the\n * selection policy in code and test on Safari/iOS + WebViews.\n *\n * ✅ What this list is used for\n * - Selecting a `mimeType` for `new MediaRecorder(stream, { mimeType })`.\n *\n * ❌ What this list does NOT guarantee\n * - It does NOT guarantee that the recorded output will be playable via the\n * HTML `<audio>` element in the same browser.\n *\n * Real-world caveat (important):\n * - We have observed cases where `MediaRecorder.isTypeSupported('audio/webm;codecs=opus')`\n * returned `true`, the recorder produced a Blob, but `<audio>` could not play it.\n * This can happen due to container/codec playback support differences, platform\n * quirks (especially Safari/iOS / WKWebView), or incomplete WebM playback support.\n *\n * Current selection behavior in this implementation:\n * - By default, MIME selection treats recorder support and playback support as separate\n * capabilities and probes both:\n * - Recorder capability: `MediaRecorder.isTypeSupported(type)`\n * - Playback capability: `audio.canPlayType(type)`\n * - This default can be disabled via `RecordingOptions.requirePlaybackSupport = false`\n * to fall back to recorder-only probing.\n *\n * Keeping legacy keys:\n * - Some entries are kept even if they overlap (e.g. `audio/mp4` and explicit codec),\n * to maximize compatibility across differing browser implementations.\n */\nconst POSSIBLE_MIME_TYPES: Record<string, string> = {\n // ✅ Most universal\n 'audio/mp4;codecs=\"mp4a.40.2\"': '.m4a', // AAC in MP4 (explicit codec helps detection)\n 'audio/mp4': '.m4a', // (legacy key kept; broad support)\n 'audio/aac': '.aac', // (legacy key kept; less common in the wild)\n 'audio/mpeg': '.mp3', // MP3 (universal)\n 'audio/wav': '.wav', // WAV (universal, big files)\n\n // ✅ Modern high-quality (very widely supported, but slightly less “universal” than MP3/AAC)\n 'audio/webm;codecs=\"opus\"': '.webm', // Opus in WebM (explicit codec helps detection)\n 'audio/webm;codecs=opus': '.webm', // (legacy key kept)\n 'audio/webm': '.webm', // (legacy key kept; container-only, codec-dependent)\n\n // ⚠️ Least universal (Safari/iOS historically the limiting factor)\n 'audio/ogg;codecs=opus': '.ogg', // (legacy key kept)\n 'audio/ogg;codecs=vorbis': '.ogg', // Ogg Vorbis (weakest mainstream support)\n};\n\n/** Creates a promise that never resolves. */\nconst neverResolvingPromise = (): Promise<any> => new Promise(() => undefined);\n\n/** Browser implementation backed by MediaRecorder and Capacitor Filesystem. */\nexport class VoiceRecorderImpl {\n /** Default behavior for web MIME selection: require recorder + playback support. */\n private static readonly DEFAULT_REQUIRE_PLAYBACK_SUPPORT = true;\n /** Active MediaRecorder instance, if recording. */\n private mediaRecorder: MediaRecorder | null = null;\n /** MIME type selected at start time for the active recording. */\n private activeMimeType: keyof typeof POSSIBLE_MIME_TYPES | null = null;\n /** Collected data chunks from MediaRecorder. */\n private chunks: any[] = [];\n /** Promise resolved when the recorder stops and payload is ready. */\n private pendingResult: Promise<RecordingData> = neverResolvingPromise();\n\n /**\n * Returns whether the browser can start a recording session.\n *\n * On web this checks:\n * - `navigator.mediaDevices.getUserMedia`\n * - at least one supported recording MIME type using {@link getSupportedMimeType}\n *\n * The optional `requirePlaybackSupport` flag is forwarded to MIME selection and defaults\n * to `true` when omitted.\n */\n public static async canDeviceVoiceRecord(\n options?: Pick<RecordingOptions, 'requirePlaybackSupport'>,\n ): Promise<GenericResponse> {\n if (\n navigator?.mediaDevices?.getUserMedia == null ||\n VoiceRecorderImpl.getSupportedMimeType({\n requirePlaybackSupport: options?.requirePlaybackSupport,\n }) == null\n ) {\n return failureResponse();\n } else {\n return successResponse();\n }\n }\n\n /**\n * Starts a recording session using `MediaRecorder`.\n *\n * The selected MIME type is resolved once at start time (using the optional\n * `requirePlaybackSupport` flag from `RecordingOptions`) and reused for the final Blob\n * and file extension to keep the recording payload internally consistent.\n */\n public async startRecording(options?: RecordingOptions): Promise<GenericResponse> {\n if (this.mediaRecorder != null) {\n throw alreadyRecordingError();\n }\n const deviceCanRecord = await VoiceRecorderImpl.canDeviceVoiceRecord(options);\n if (!deviceCanRecord.value) {\n throw deviceCannotVoiceRecordError();\n }\n const havingPermission = await VoiceRecorderImpl.hasAudioRecordingPermission().catch(() => successResponse());\n if (!havingPermission.value) {\n throw missingPermissionError();\n }\n\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then((stream) => this.onSuccessfullyStartedRecording(stream, options))\n .catch(this.onFailedToStartRecording.bind(this));\n }\n\n /** Stops the current recording and resolves the pending payload. */\n public async stopRecording(): Promise<RecordingData> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n }\n try {\n this.mediaRecorder.stop();\n this.mediaRecorder.stream.getTracks().forEach((track) => track.stop());\n return this.pendingResult;\n } catch (ignore) {\n throw failedToFetchRecordingError();\n } finally {\n this.prepareInstanceForNextOperation();\n }\n }\n\n /** Returns whether the browser has microphone permission. */\n public static async hasAudioRecordingPermission(): Promise<GenericResponse> {\n // Safari does not support navigator.permissions.query\n if (!navigator.permissions.query) {\n if (navigator.mediaDevices !== undefined) {\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then(() => successResponse())\n .catch(() => {\n throw couldNotQueryPermissionStatusError();\n });\n }\n }\n return navigator.permissions\n .query({name: 'microphone' as any})\n .then((result) => ({value: result.state === 'granted'}))\n .catch(() => {\n throw couldNotQueryPermissionStatusError();\n });\n }\n\n /** Requests microphone permission from the browser. */\n public static async requestAudioRecordingPermission(): Promise<GenericResponse> {\n const havingPermission = await VoiceRecorderImpl.hasAudioRecordingPermission().catch(() => failureResponse());\n if (havingPermission.value) {\n return successResponse();\n }\n\n return navigator.mediaDevices\n .getUserMedia({audio: true})\n .then(() => successResponse())\n .catch(() => failureResponse());\n }\n\n /** Pauses the recording session when supported. */\n public pauseRecording(): Promise<GenericResponse> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n } else if (this.mediaRecorder.state === 'recording') {\n this.mediaRecorder.pause();\n return Promise.resolve(successResponse());\n } else {\n return Promise.resolve(failureResponse());\n }\n }\n\n /** Resumes a paused recording session when supported. */\n public resumeRecording(): Promise<GenericResponse> {\n if (this.mediaRecorder == null) {\n throw recordingHasNotStartedError();\n } else if (this.mediaRecorder.state === 'paused') {\n this.mediaRecorder.resume();\n return Promise.resolve(successResponse());\n } else {\n return Promise.resolve(failureResponse());\n }\n }\n\n /** Returns the current recording status from MediaRecorder. */\n public getCurrentStatus(): Promise<CurrentRecordingStatus> {\n if (this.mediaRecorder == null) {\n return Promise.resolve({status: 'NONE'});\n } else if (this.mediaRecorder.state === 'recording') {\n return Promise.resolve({status: 'RECORDING'});\n } else if (this.mediaRecorder.state === 'paused') {\n return Promise.resolve({status: 'PAUSED'});\n } else {\n return Promise.resolve({status: 'NONE'});\n }\n }\n\n /**\n * Returns the first MIME type (key of {@link POSSIBLE_MIME_TYPES}) that the current\n * environment reports as supported for recording via `MediaRecorder.isTypeSupported()`,\n * optionally requiring native HTML `<audio>` playback support too.\n *\n * The search order is the iteration order of {@link POSSIBLE_MIME_TYPES}.\n *\n * @typeParam T - A MIME type string that exists as a key in {@link POSSIBLE_MIME_TYPES}.\n *\n * @returns The first supported MIME type for `MediaRecorder`, or `null` if:\n * - `MediaRecorder` is unavailable, or\n * - no configured MIME types are supported.\n *\n * ⚠️ Important: `MediaRecorder` support ≠ `<audio>` playback support\n *\n * Some browsers/platforms can claim support for recording a format (notably WebM/Opus)\n * but still fail to play the resulting Blob through the native HTML audio pipeline.\n * This mismatch is especially likely on Safari/iOS / WKWebView variants, so the default\n * behavior also probes `HTMLAudioElement.canPlayType(type)` when available.\n *\n * Selection policy when playback probing is enabled:\n * - keep the global priority order from {@link POSSIBLE_MIME_TYPES}\n * - among recordable types, prefer the first `\"probably\"` playable candidate\n * - otherwise return the first `\"maybe\"` playable candidate\n * - treat `\"\"` as not playable\n *\n * Note: The <audio> element is never attached to the DOM, so it won't appear to users or assistive tech.\n *\n * Fallback behavior:\n * - If `document` / `audio.canPlayType` is unavailable (e.g. SSR-like environments),\n * this falls back to record-only probing.\n */\n public static getSupportedMimeType<T extends keyof typeof POSSIBLE_MIME_TYPES>(\n options?: { requirePlaybackSupport?: boolean },\n ): T | null {\n if (MediaRecorder?.isTypeSupported == null) return null;\n\n const orderedTypes = Object.keys(POSSIBLE_MIME_TYPES) as T[];\n const recordSupportedTypes = orderedTypes.filter((type) => MediaRecorder.isTypeSupported(type));\n if (recordSupportedTypes.length === 0) return null;\n\n const requirePlaybackSupport =\n options?.requirePlaybackSupport ?? VoiceRecorderImpl.DEFAULT_REQUIRE_PLAYBACK_SUPPORT;\n if (!requirePlaybackSupport) {\n return recordSupportedTypes[0] ?? null;\n }\n\n if (typeof document === 'undefined' || typeof document.createElement !== 'function') {\n return recordSupportedTypes[0] ?? null;\n }\n\n const audioElement = document.createElement('audio') as Partial<HTMLAudioElement>;\n if (typeof audioElement.canPlayType !== 'function') {\n return recordSupportedTypes[0] ?? null;\n }\n\n let firstProbably: T | null = null;\n let firstMaybe: T | null = null;\n\n for (const type of recordSupportedTypes) {\n const playbackSupport = audioElement.canPlayType(type);\n if (playbackSupport === 'probably') {\n firstProbably = type;\n break;\n }\n if (playbackSupport === 'maybe' && firstMaybe == null) {\n firstMaybe = type;\n }\n }\n\n return firstProbably ?? firstMaybe ?? null;\n }\n\n /** Initializes MediaRecorder and wires up handlers. */\n private onSuccessfullyStartedRecording(stream: MediaStream, options?: RecordingOptions): GenericResponse {\n this.pendingResult = new Promise((resolve, reject) => {\n const mimeType = VoiceRecorderImpl.getSupportedMimeType({\n requirePlaybackSupport: options?.requirePlaybackSupport,\n });\n if (mimeType == null) {\n this.prepareInstanceForNextOperation();\n reject(failedToRecordError());\n return;\n }\n\n this.activeMimeType = mimeType;\n this.mediaRecorder = new MediaRecorder(stream, {mimeType});\n this.mediaRecorder.onerror = () => {\n this.prepareInstanceForNextOperation();\n reject(failedToRecordError());\n };\n this.mediaRecorder.onstop = async () => {\n const finalMimeType = this.activeMimeType;\n if (finalMimeType == null) {\n this.prepareInstanceForNextOperation();\n reject(failedToFetchRecordingError());\n return;\n }\n const blobVoiceRecording = new Blob(this.chunks, {type: finalMimeType});\n if (blobVoiceRecording.size <= 0) {\n this.prepareInstanceForNextOperation();\n reject(emptyRecordingError());\n return;\n }\n\n let uri: string | undefined = undefined;\n let recordDataBase64 = '';\n if (options?.directory) {\n const subDirectory = options.subDirectory?.match(/^\\/?(.+[^/])\\/?$/)?.[1] ?? '';\n const path = `${subDirectory}/recording-${new Date().getTime()}${POSSIBLE_MIME_TYPES[finalMimeType]}`;\n\n await write_blob({\n blob: blobVoiceRecording,\n directory: options.directory,\n fast_mode: true,\n path,\n recursive: true,\n });\n\n ({uri} = await Filesystem.getUri({directory: options.directory, path}));\n } else {\n recordDataBase64 = await VoiceRecorderImpl.blobToBase64(blobVoiceRecording);\n }\n\n const recordingDuration = await getBlobDuration(blobVoiceRecording);\n this.prepareInstanceForNextOperation();\n resolve({\n value: {\n recordDataBase64,\n mimeType: finalMimeType,\n msDuration: recordingDuration * 1000,\n uri\n }\n });\n };\n this.mediaRecorder.ondataavailable = (event: any) => this.chunks.push(event.data);\n this.mediaRecorder.start();\n });\n return successResponse();\n }\n\n /** Handles failures from getUserMedia. */\n private onFailedToStartRecording(): GenericResponse {\n this.prepareInstanceForNextOperation();\n throw failedToRecordError();\n }\n\n /** Converts a Blob payload into a base64 string. */\n private static blobToBase64(blob: Blob): Promise<Base64String> {\n return new Promise((resolve) => {\n const reader = new FileReader();\n reader.onloadend = () => {\n const recordingResult = String(reader.result);\n const splitResult = recordingResult.split('base64,');\n const toResolve = splitResult.length > 1 ? splitResult[1] : recordingResult;\n resolve(toResolve.trim());\n };\n reader.readAsDataURL(blob);\n });\n }\n\n /** Resets state for the next recording attempt. */\n private prepareInstanceForNextOperation(): void {\n if (this.mediaRecorder != null && this.mediaRecorder.state === 'recording') {\n try {\n this.mediaRecorder.stop();\n } catch (ignore) {\n console.warn('Failed to stop recording during cleanup');\n }\n }\n this.pendingResult = neverResolvingPromise();\n this.mediaRecorder = null;\n this.activeMimeType = null;\n this.chunks = [];\n }\n}\n"]}