React Native 如果用户没有停止录制,如何在15秒后自动停止录制?

mi7gmzs6  于 2023-03-24  发布在  React
关注(0)|答案(3)|浏览(183)
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [recording, setRecording] = React.useState();

  async function startRecording() {
    try {
      console.log('Requesting permissions..');
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      });

      console.log('Starting recording..');
      const { recording } = await Audio.Recording.createAsync( Audio.RecordingOptionsPresets.HIGH_QUALITY
      );
      setRecording(recording);
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

  async function stopRecording() {
    console.log('Stopping recording..');
    setRecording(undefined);
    await recording.stopAndUnloadAsync();
    await Audio.setAudioModeAsync({
      allowsRecordingIOS: false,
    });
    const uri = recording.getURI();
    console.log('Recording stopped and stored at', uri);
  }

  return (
    <View>
      <Button
        title={recording ? 'Stop Recording' : 'Start Recording'}
        onPress={recording ? stopRecording : startRecording}
      /> 
    </View>
  );
}

我的代码在按下按钮时录制音频,再次按下按钮时停止录制。如果用户尚未按下停止按钮,如何修改代码以在录制到15秒时自动停止录制?

inn6fuwd

inn6fuwd1#

尝试使用setTimeout

useEffect(() => {
  if (recording) {
    const timer = setTimeout(() => {
      stopRecording()
    }, 15000)

    return () => clearTimeout(timer);
  }
}, [recording])
cx6n0qe3

cx6n0qe32#

可以设置15秒的超时,如果仍在记录,则调用stopRecording函数。

setTimeout(() => {
  stopRecording();
}, 15000);
42fyovps

42fyovps3#

我想你要找的是setTimeout函数。
文档可在此处找到:https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
对于您的用例,您可以创建一个新函数来处理15秒的录音。它可能看起来像这样:

async function recordFor15Seconds() {
  startRecording();
  setTimeout(() => {
    stopRecording();
  }, 15000);
}

相关问题