diff --git a/packages/website-astro/public/llms-full.txt b/packages/website-astro/public/llms-full.txt index a9bd5290..328900aa 100644 --- a/packages/website-astro/public/llms-full.txt +++ b/packages/website-astro/public/llms-full.txt @@ -3730,7 +3730,7 @@ function Demo() { --- -# Browser hooks (49) +# Browser hooks (50) ## useBroadcastChannel @@ -5767,6 +5767,147 @@ function Demo() { --- +## useMicrophone + +URL: https://reactuse.com/browser/usemicrophone/ +Category: browser +Description: useMicrophone is a React hook for the microphone — open a stream, read a real-time audio level, and record audio to a Blob with MediaRecorder. +Import: `import { useMicrophone } from '@reactuses/core'` + +# useMicrophone + +React hook for capturing microphone audio + +`useMicrophone` wraps [`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API), and [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) into a single hook. It opens and closes the microphone stream, exposes a throttled audio `level` (0–1, RMS) suitable for a VU meter, and records the active stream to a `Blob` with a hook-managed object URL. + +The live-stream controls (`start` / `stop`) and the recording controls (`startRecording` / `stopRecording` / `pauseRecording` / `resumeRecording`) are independent: you can show a level meter without recording, and start or stop a recording without dropping the microphone. + +### When to Use + +- Building voice-note or dictation UIs where the user sees a live input level before and while recording +- Adding "speak now" prompts or microphone calibration screens that need a VU meter but no capture +- Recording short audio clips to a `Blob` for upload or local playback + +### Notes + +- **SSR-safe**: Returns `isSupported: false` and no-op controls during server-side rendering. No `navigator.mediaDevices` access occurs on the server. +- **`start()` before `startRecording()`**: Recording captures an already-open stream. Call `start()` first; calling `startRecording()` without an active stream sets `error` instead of recording. +- **HTTPS required**: In production the microphone requires a secure context (HTTPS). The browser prompts for permission on the first `start()`. +- **Object URL lifecycle**: `audioUrl` is created and revoked by the hook — it is replaced on the next recording and revoked on unmount, so consumers do not need to call `URL.revokeObjectURL` themselves. +- **Mime type**: The recording format is auto-selected from the formats the browser supports (`audio/webm;codecs=opus`, `audio/webm`, `audio/mp4`, `audio/ogg;codecs=opus`). The resolved value is exposed as `mimeType`. +- **Related hooks**: Use `useMediaDevices` to enumerate microphones and pass a `deviceId`, or `useSpeechRecognition` for speech-to-text. + +## Usage + +```tsx live +function Demo() { + const { + isSupported, + isActive, + level, + isRecording, + isPaused, + audioUrl, + mimeType, + error, + start, + stop, + startRecording, + stopRecording, + pauseRecording, + resumeRecording, + } = useMicrophone(); + + if (!isSupported) { + return
Microphone is not supported in this browser
; + } + + const levelPercent = Math.round(level * 100); + + return ( +
+
+

+ Microphone: {isActive ? 'Open' : 'Closed'} + {' · '} + Recording:{' '} + {isRecording ? (isPaused ? 'Paused' : 'Recording...') : 'Idle'} +

+ +
+
70 + ? 'var(--ifm-color-danger)' + : 'var(--ifm-color-success)', + transition: 'width 80ms linear', + }} + /> +
+

+ Input level: {levelPercent}% +

+
+ +
+ + + + + + +
+ + {audioUrl && ( +
+

+ Recorded clip ({mimeType || 'default format'}): +

+
+ )} + + {error && ( +

+ Error: {error.message} +

+ )} +
+ ); +} +``` + +## Common Use Cases + +- **Voice notes**: Open the mic so the user sees a live level, then record to a `Blob` and play it back or upload it. +- **Level metering**: Drive a VU meter or waveform from `level` without recording anything. +- **Microphone calibration**: Let users confirm the right device is picked up before they start. + +--- + ## useMobileLandscape URL: https://reactuse.com/browser/usemobilelandscape/ @@ -7685,4 +7826,4 @@ function Demo() { --- -Generated: 2026-05-14T09:08:21.446Z | Total hooks: 113 +Generated: 2026-05-20T20:21:53.456Z | Total hooks: 114 diff --git a/packages/website-astro/public/llms.txt b/packages/website-astro/public/llms.txt index 11c5164b..ae330392 100644 --- a/packages/website-astro/public/llms.txt +++ b/packages/website-astro/public/llms.txt @@ -619,7 +619,7 @@ React Element Hooks that tracks window size Documentation: https://reactuse.com/element/usewindowsize/ Import: `import { useWindowSize } from '@reactuses/core'` -### Browser (49 hooks) +### Browser (50 hooks) #### useBroadcastChannel @@ -828,6 +828,15 @@ Ease with media query Documentation: https://reactuse.com/browser/usemediaquery/ Import: `import { useMediaQuery } from '@reactuses/core'` +#### useMicrophone + +useMicrophone is a React hook for the microphone — open a stream, read a real-time audio level, and record audio to a Blob with MediaRecorder. + +React hook for capturing microphone audio + +Documentation: https://reactuse.com/browser/usemicrophone/ +Import: `import { useMicrophone } from '@reactuses/core'` + #### useMobileLandscape useMobileLandscape is a React hook that returns true when the device is a mobile in landscape orientation, updating reactively on rotation. @@ -1101,4 +1110,4 @@ PDD (Pinduoduo), Shopee, Ctrip, Bambu Lab Unlicense - Use freely without restrictions --- -Generated: 2026-05-14T09:08:21.396Z | Total Hooks: 113 +Generated: 2026-05-20T20:21:53.426Z | Total Hooks: 114 diff --git a/packages/website-astro/src/content/docs-zh-hans/browser/useMicrophone.mdx b/packages/website-astro/src/content/docs-zh-hans/browser/useMicrophone.mdx new file mode 100644 index 00000000..b9df42c4 --- /dev/null +++ b/packages/website-astro/src/content/docs-zh-hans/browser/useMicrophone.mdx @@ -0,0 +1,138 @@ +--- +title: useMicrophone 用法与示例 +sidebar_label: useMicrophone +description: "useMicrophone 是一个用于麦克风的 React hook,可打开音频流、读取实时音量电平,并通过 MediaRecorder 将音频录制为 Blob。" +--- +# useMicrophone + +用于采集麦克风音频的 React hook + +`useMicrophone` 将 [`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)、[Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API) 和 [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) 封装进同一个 hook。它负责打开和关闭麦克风音频流,暴露一个经过节流的音量 `level`(0–1,RMS),适合用于音量条,并可将当前音频流录制为 `Blob`,同时由 hook 管理对象 URL 的生命周期。 + +实时音频流控制(`start` / `stop`)与录音控制(`startRecording` / `stopRecording` / `pauseRecording` / `resumeRecording`)相互独立:你可以只显示音量条而不录音,也可以在不关闭麦克风的情况下开始或停止录音。 + +### 使用场景 + +- 构建语音备忘录或听写界面,让用户在录音前和录音中都能看到实时输入电平 +- 添加「请说话」提示或麦克风校准界面 —— 需要音量条但不需要录音 +- 将短音频片段录制为 `Blob` 用于上传或本地播放 + +### 注意事项 + +- **SSR 安全**:在服务端渲染期间返回 `isSupported: false` 和空操作的控制函数。服务端不会访问 `navigator.mediaDevices`。 +- **先 `start()` 再 `startRecording()`**:录音采集的是已打开的音频流。请先调用 `start()`;在没有活动流时调用 `startRecording()` 会设置 `error` 而不会开始录音。 +- **需要 HTTPS**:在生产环境中,麦克风需要安全上下文(HTTPS)。浏览器会在首次 `start()` 时请求权限。 +- **对象 URL 生命周期**:`audioUrl` 由 hook 创建和释放 —— 它会在下一次录音时被替换,并在卸载时被释放,因此使用方无需自行调用 `URL.revokeObjectURL`。 +- **Mime 类型**:录音格式会从浏览器支持的格式中自动选择(`audio/webm;codecs=opus`、`audio/webm`、`audio/mp4`、`audio/ogg;codecs=opus`)。最终解析出的值通过 `mimeType` 暴露。 +- **相关 hooks**:使用 `useMediaDevices` 枚举麦克风并传入 `deviceId`,或使用 `useSpeechRecognition` 进行语音转文字。 + +## 基本用法 + +```tsx live +function Demo() { + const { + isSupported, + isActive, + level, + isRecording, + isPaused, + audioUrl, + mimeType, + error, + start, + stop, + startRecording, + stopRecording, + pauseRecording, + resumeRecording, + } = useMicrophone(); + + if (!isSupported) { + return
此浏览器不支持麦克风
; + } + + const levelPercent = Math.round(level * 100); + + return ( +
+
+

+ 麦克风: {isActive ? '已打开' : '已关闭'} + {' · '} + 录音:{' '} + {isRecording ? (isPaused ? '已暂停' : '录音中...') : '空闲'} +

+ +
+
70 + ? 'var(--ifm-color-danger)' + : 'var(--ifm-color-success)', + transition: 'width 80ms linear', + }} + /> +
+

+ 输入电平: {levelPercent}% +

+
+ +
+ + + + + + +
+ + {audioUrl && ( +
+

+ 录制的片段({mimeType || '默认格式'}): +

+
+ )} + + {error && ( +

+ 错误: {error.message} +

+ )} +
+ ); +} +``` + +## 常见用例 + +- **语音备忘录**:打开麦克风让用户看到实时电平,然后录制为 `Blob` 并回放或上传。 +- **音量监测**:用 `level` 驱动音量条或波形,而无需录制任何内容。 +- **麦克风校准**:让用户在开始前确认采集到的是正确的设备。 + +%%API%% diff --git a/packages/website-astro/src/content/docs-zh-hant/browser/useMicrophone.mdx b/packages/website-astro/src/content/docs-zh-hant/browser/useMicrophone.mdx new file mode 100644 index 00000000..85ed8c56 --- /dev/null +++ b/packages/website-astro/src/content/docs-zh-hant/browser/useMicrophone.mdx @@ -0,0 +1,138 @@ +--- +title: useMicrophone 用法與示例 +sidebar_label: useMicrophone +description: "useMicrophone 是一個用於麥克風的 React hook,可開啟音訊串流、讀取即時音量電平,並透過 MediaRecorder 將音訊錄製為 Blob。" +--- +# useMicrophone + +用於擷取麥克風音訊的 React hook + +`useMicrophone` 將 [`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)、[Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API) 和 [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) 封裝進同一個 hook。它負責開啟和關閉麥克風音訊串流,提供一個經過節流的音量 `level`(0–1,RMS),適合用於音量條,並可將目前的音訊串流錄製為 `Blob`,同時由 hook 管理物件 URL 的生命週期。 + +即時音訊串流控制(`start` / `stop`)與錄音控制(`startRecording` / `stopRecording` / `pauseRecording` / `resumeRecording`)彼此獨立:你可以只顯示音量條而不錄音,也可以在不關閉麥克風的情況下開始或停止錄音。 + +### 使用場景 + +- 建構語音備忘錄或聽寫介面,讓使用者在錄音前和錄音中都能看到即時輸入電平 +- 加入「請說話」提示或麥克風校準介面 —— 需要音量條但不需要錄音 +- 將短音訊片段錄製為 `Blob` 用於上傳或本機播放 + +### 注意事項 + +- **SSR 安全**:在伺服器端渲染期間回傳 `isSupported: false` 和空操作的控制函式。伺服器端不會存取 `navigator.mediaDevices`。 +- **先 `start()` 再 `startRecording()`**:錄音擷取的是已開啟的音訊串流。請先呼叫 `start()`;在沒有活動串流時呼叫 `startRecording()` 會設定 `error` 而不會開始錄音。 +- **需要 HTTPS**:在生產環境中,麥克風需要安全內容(HTTPS)。瀏覽器會在首次 `start()` 時請求權限。 +- **物件 URL 生命週期**:`audioUrl` 由 hook 建立和釋放 —— 它會在下一次錄音時被取代,並在卸載時被釋放,因此使用方無需自行呼叫 `URL.revokeObjectURL`。 +- **Mime 類型**:錄音格式會從瀏覽器支援的格式中自動選擇(`audio/webm;codecs=opus`、`audio/webm`、`audio/mp4`、`audio/ogg;codecs=opus`)。最終解析出的值透過 `mimeType` 提供。 +- **相關 hooks**:使用 `useMediaDevices` 列舉麥克風並傳入 `deviceId`,或使用 `useSpeechRecognition` 進行語音轉文字。 + +## 基本用法 + +```tsx live +function Demo() { + const { + isSupported, + isActive, + level, + isRecording, + isPaused, + audioUrl, + mimeType, + error, + start, + stop, + startRecording, + stopRecording, + pauseRecording, + resumeRecording, + } = useMicrophone(); + + if (!isSupported) { + return
此瀏覽器不支援麥克風
; + } + + const levelPercent = Math.round(level * 100); + + return ( +
+
+

+ 麥克風: {isActive ? '已開啟' : '已關閉'} + {' · '} + 錄音:{' '} + {isRecording ? (isPaused ? '已暫停' : '錄音中...') : '閒置'} +

+ +
+
70 + ? 'var(--ifm-color-danger)' + : 'var(--ifm-color-success)', + transition: 'width 80ms linear', + }} + /> +
+

+ 輸入電平: {levelPercent}% +

+
+ +
+ + + + + + +
+ + {audioUrl && ( +
+

+ 錄製的片段({mimeType || '預設格式'}): +

+
+ )} + + {error && ( +

+ 錯誤: {error.message} +

+ )} +
+ ); +} +``` + +## 常見用例 + +- **語音備忘錄**:開啟麥克風讓使用者看到即時電平,然後錄製為 `Blob` 並回放或上傳。 +- **音量監測**:用 `level` 驅動音量條或波形,而無需錄製任何內容。 +- **麥克風校準**:讓使用者在開始前確認擷取到的是正確的裝置。 + +%%API%% diff --git a/packages/website-astro/src/content/docs/browser/useMicrophone.mdx b/packages/website-astro/src/content/docs/browser/useMicrophone.mdx new file mode 100644 index 00000000..87d682ae --- /dev/null +++ b/packages/website-astro/src/content/docs/browser/useMicrophone.mdx @@ -0,0 +1,138 @@ +--- +title: useMicrophone – Browser Hook Usage & Examples +sidebar_label: useMicrophone +description: "useMicrophone is a React hook for the microphone — open a stream, read a real-time audio level, and record audio to a Blob with MediaRecorder." +--- +# useMicrophone + +React hook for capturing microphone audio + +`useMicrophone` wraps [`getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API), and [`MediaRecorder`](https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder) into a single hook. It opens and closes the microphone stream, exposes a throttled audio `level` (0–1, RMS) suitable for a VU meter, and records the active stream to a `Blob` with a hook-managed object URL. + +The live-stream controls (`start` / `stop`) and the recording controls (`startRecording` / `stopRecording` / `pauseRecording` / `resumeRecording`) are independent: you can show a level meter without recording, and start or stop a recording without dropping the microphone. + +### When to Use + +- Building voice-note or dictation UIs where the user sees a live input level before and while recording +- Adding "speak now" prompts or microphone calibration screens that need a VU meter but no capture +- Recording short audio clips to a `Blob` for upload or local playback + +### Notes + +- **SSR-safe**: Returns `isSupported: false` and no-op controls during server-side rendering. No `navigator.mediaDevices` access occurs on the server. +- **`start()` before `startRecording()`**: Recording captures an already-open stream. Call `start()` first; calling `startRecording()` without an active stream sets `error` instead of recording. +- **HTTPS required**: In production the microphone requires a secure context (HTTPS). The browser prompts for permission on the first `start()`. +- **Object URL lifecycle**: `audioUrl` is created and revoked by the hook — it is replaced on the next recording and revoked on unmount, so consumers do not need to call `URL.revokeObjectURL` themselves. +- **Mime type**: The recording format is auto-selected from the formats the browser supports (`audio/webm;codecs=opus`, `audio/webm`, `audio/mp4`, `audio/ogg;codecs=opus`). The resolved value is exposed as `mimeType`. +- **Related hooks**: Use `useMediaDevices` to enumerate microphones and pass a `deviceId`, or `useSpeechRecognition` for speech-to-text. + +## Usage + +```tsx live +function Demo() { + const { + isSupported, + isActive, + level, + isRecording, + isPaused, + audioUrl, + mimeType, + error, + start, + stop, + startRecording, + stopRecording, + pauseRecording, + resumeRecording, + } = useMicrophone(); + + if (!isSupported) { + return
Microphone is not supported in this browser
; + } + + const levelPercent = Math.round(level * 100); + + return ( +
+
+

+ Microphone: {isActive ? 'Open' : 'Closed'} + {' · '} + Recording:{' '} + {isRecording ? (isPaused ? 'Paused' : 'Recording...') : 'Idle'} +

+ +
+
70 + ? 'var(--ifm-color-danger)' + : 'var(--ifm-color-success)', + transition: 'width 80ms linear', + }} + /> +
+

+ Input level: {levelPercent}% +

+
+ +
+ + + + + + +
+ + {audioUrl && ( +
+

+ Recorded clip ({mimeType || 'default format'}): +

+
+ )} + + {error && ( +

+ Error: {error.message} +

+ )} +
+ ); +} +``` + +## Common Use Cases + +- **Voice notes**: Open the mic so the user sees a live level, then record to a `Blob` and play it back or upload it. +- **Level metering**: Drive a VU meter or waveform from `level` without recording anything. +- **Microphone calibration**: Let users confirm the right device is picked up before they start. + +%%API%% diff --git a/packages/website-docusaurus/api/useMicrophone-README-zhHans.md b/packages/website-docusaurus/api/useMicrophone-README-zhHans.md new file mode 100644 index 00000000..3fc76aaf --- /dev/null +++ b/packages/website-docusaurus/api/useMicrophone-README-zhHans.md @@ -0,0 +1,19 @@ +### UseMicrophoneOptions + +|参数名|描述|类型|默认值| +|---|---|---|---| +|deviceId|指定要使用的麦克风设备 ID;激活状态下变化会自动重新获取流|string |`-`| +|constraints|与默认音频约束合并的额外 MediaTrackConstraints;deviceId 优先|MediaTrackConstraints |`-`| +|levelInterval|音量级别状态更新的节流间隔(毫秒)|number |`-`| +|mimeType|MediaRecorder 的首选 mime 类型;不受支持时自动回退|string |`-`| +|autoStart|挂载时自动打开麦克风|boolean |`-`| + +### useMicrophone + +#### Returns +`UseMicrophoneReturn`: 包含麦克风流、音量级别、录音控制等的对象 + +#### Arguments +|参数名|描述|类型|默认值| +|---|---|---|---| +|options|可选配置|[UseMicrophoneOptions](#usemicrophoneoptions) \| undefined |-| \ No newline at end of file diff --git a/packages/website-docusaurus/api/useMicrophone-README-zhHant.md b/packages/website-docusaurus/api/useMicrophone-README-zhHant.md new file mode 100644 index 00000000..f163cc76 --- /dev/null +++ b/packages/website-docusaurus/api/useMicrophone-README-zhHant.md @@ -0,0 +1,19 @@ +### UseMicrophoneOptions + +|參數名|描述|類型|預設值| +|---|---|---|---| +|deviceId|指定要使用的麦克风设备 ID;激活状态下变化会自动重新获取流|string |`-`| +|constraints|与默认音频约束合并的额外 MediaTrackConstraints;deviceId 优先|MediaTrackConstraints |`-`| +|levelInterval|音量级别状态更新的节流间隔(毫秒)|number |`-`| +|mimeType|MediaRecorder 的首选 mime 类型;不受支持时自动回退|string |`-`| +|autoStart|挂载时自动打开麦克风|boolean |`-`| + +### useMicrophone + +#### Returns +`UseMicrophoneReturn`: 包含麥克風串流、音量等級、錄音控制等的物件 + +#### Arguments +|參數名|描述|類型|預設值| +|---|---|---|---| +|options|可选配置|[UseMicrophoneOptions](#usemicrophoneoptions) \| undefined |-| \ No newline at end of file diff --git a/packages/website-docusaurus/api/useMicrophone-README.md b/packages/website-docusaurus/api/useMicrophone-README.md new file mode 100644 index 00000000..06e7ab6d --- /dev/null +++ b/packages/website-docusaurus/api/useMicrophone-README.md @@ -0,0 +1,19 @@ +### UseMicrophoneOptions + +|Property|Description|Type|DefaultValue| +|---|---|---|---| +|deviceId|Specific microphone deviceId; re-acquires the stream when changed while active|string |`-`| +|constraints|Extra MediaTrackConstraints merged with the defaults; deviceId above takes precedence|MediaTrackConstraints |`-`| +|levelInterval|Throttle interval (ms) for level state updates|number |`-`| +|mimeType|Preferred MediaRecorder mime type; falls back to auto-selection if unsupported|string |`-`| +|autoStart|Automatically open the microphone on mount|boolean |`-`| + +### useMicrophone + +#### Returns +`UseMicrophoneReturn`: An object exposing the microphone stream, audio level, recording controls, and lifecycle methods + +#### Arguments +|Argument|Description|Type|DefaultValue| +|---|---|---|---| +|options|Optional configuration|[UseMicrophoneOptions](#usemicrophoneoptions) \| undefined |-| \ No newline at end of file diff --git a/scripts/hook-registry.json b/scripts/hook-registry.json index 70670f45..5278cfb9 100644 --- a/scripts/hook-registry.json +++ b/scripts/hook-registry.json @@ -239,6 +239,10 @@ "category": "state", "url": "https://reactuse.com/state/usemergedrefs/" }, + "useMicrophone": { + "category": "browser", + "url": "https://reactuse.com/browser/usemicrophone/" + }, "useMobileLandscape": { "category": "browser", "url": "https://reactuse.com/browser/usemobilelandscape/"