useRecord
录音操作等.
何时使用
当需要进行录音操作时
API
const [recorderManager, { start, stop }] = useRecord();
参数说明
无
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
recorderManager | 全局唯一录音管理器 | RecorderManager |
start | 开始录音 | (option: RecorderManager.StartOption) => Promise<General.CallbackResult> |
stop | 结束录音 | PromiseWithoutOptionAction<RecorderManager.OnStopCallbackResult> |
代码演示
- React
- Vue
media/useAudio/index
import React from 'react';
import { useState } from '@taro-hooks/core';
import { useToast, useRecord, useAudio } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button } from '@taroify/core';
export default () => {
const [audioSource, setAudioSource] =
useState<Taro.RecorderManager.OnStopCallbackResult>();
const [audioContext, { play }] = useAudio();
const [, { start, stop }] = useRecord();
const { show } = useToast({
title: 'useVoice',
duration: 500,
mask: true,
});
const handleStop = async () => {
try {
show({ title: '正在停止', duration: 20000000 });
const result = await stop();
setAudioSource(result);
show({ title: '停止录制成功' });
} catch (e) {
show({ title: '停止录制失败', icon: 'error' });
}
};
return (
<DemoContent>
<Button
block
color="primary"
className="gap"
onClick={() => start()}
shape="square"
>
开始录制
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleStop()}
shape="square"
>
结束录制
</Button>
<Button
block
color="primary"
className="gap"
disabled={!audioSource?.tempFilePath}
onClick={() => play(audioSource?.tempFilePath)}
shape="square"
>
播放音频
</Button>
<Button
block
color="primary"
className="gap"
disabled={!audioSource?.tempFilePath}
onClick={() => audioContext?.stop?.()}
shape="square"
>
停止播放音频
</Button>
</DemoContent>
);
};
media/useAudio/index
<template>
<demo-content>
<nut-button shape="square" type="primary" class="gap" block @click="start()"
>开始录制</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleStop()"
>结束录制</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
:disabled="!audioSource?.tempFilePath"
@click="play(audioSource?.tempFilePath)"
>播放音频</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
:disabled="!audioSource?.tempFilePath"
@click="audioContext?.stop?.()"
>停止播放音频</nut-button
>
</demo-content>
</template>
<script setup lang="ts">
import { useState } from '@taro-hooks/core';
import { useToast, useRecord, useAudio } from 'taro-hooks';
const [audioSource, setAudioSource] =
useState<Taro.RecorderManager.OnStopCallbackResult>();
const [audioContext, { play }] = useAudio();
const [, { start, stop }] = useRecord();
const { show } = useToast({
title: 'useVoice',
duration: 500,
mask: true,
});
const handleStop = async () => {
try {
show({ title: '正在停止', duration: 20000000 });
const result = await stop();
setAudioSource(result);
show({ title: '停止录制成功' });
} catch (e) {
show({ title: '停止录制失败', icon: 'error' });
}
};
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ |