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秒时自动停止录制?
3条答案
按热度按时间inn6fuwd1#
尝试使用
setTimeout
:cx6n0qe32#
可以设置15秒的超时,如果仍在记录,则调用stopRecording函数。
42fyovps3#
我想你要找的是
setTimeout
函数。文档可在此处找到:https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
对于您的用例,您可以创建一个新函数来处理15秒的录音。它可能看起来像这样: