import React, { Component } from 'react' import { View, Text, StyleSheet, TouchableOpacity, Image, TextInput, TouchableHighlight, Keyboard, KeyboardAvoidingView } from 'react-native'; import BottomSheet from 'reanimated-bottom-sheet' import Animated from 'react-native-reanimated'; import { px2dp, height, size, onePx, colors, toast, toastShort, isEmpty, handleDismissKeyboard, myConfirm, getCurrentDateNs, getFileType } from './../../utils' import redux from './../../redux/store'; import LottieView from 'lottie-react-native'; //@ts-ignore import { AudioRecorder, AudioUtils } from 'react-native-audio'; import RNFS from 'react-native-fs'; interface Props { isInTab?: boolean; onRecordFinish?: Function themeColor?: string; headerText?: string; disableReason?: string; autoStart?: boolean onClose?: Function }; interface State { height: number isRecording: boolean hasPermission: boolean audioPath: string duration: number voiceFileName: string, deviceHeight: number, keyBoardHeight: number } export default class KitRecordVoiceSheet extends Component { constructor(props: Props) { super(props); const _state = redux.getState(); this.state = { height: height, deviceHeight: _state.deviceHeight ? _state.deviceHeight : 700, isRecording: false, hasPermission: false, audioPath: "", // 文件路径 duration: 0, voiceFileName: "", keyBoardHeight: 0, }; this.renderInner = this.renderInner.bind(this) this._onCloseEnd = this._onCloseEnd.bind(this); }; public actionSheetHeaderHeight = px2dp(60); public decButtomOutLineWidth = px2dp(8) public sheetContainerRef = null; public sheetRef = null; public delayShow = null; public fall = new Animated.Value(1); public delayTimer = null; public delayHideTimer = null; public recordBtnIconRef = null; public recordStartTime = null; public keyboardDidShowListener = null; public keyboardDidHideListener = null; public sheetBoxRef = null; componentDidMount() { this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this)); this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this)); this.getAudioAuthorize() }; componentWillUnmount() { this.delayTimer && clearTimeout(this.delayTimer); this.delayHideTimer && clearTimeout(this.delayHideTimer); this.keyboardDidShowListener.remove(); this.keyboardDidHideListener.remove(); this.setState = (state, callback) => { return; } }; _keyboardDidShow(e) { this.sheetBoxRef.setNativeProps({ style: { bottom: -e.endCoordinates.height } }) } _keyboardDidHide() { this.sheetBoxRef.setNativeProps({ style: { bottom: 0 } }) } // 请求录音授权 getAudioAuthorize() { AudioRecorder.requestAuthorization() .then(isAuthor => { console.log('是否授权: ' + isAuthor) if (!isAuthor) { return alert('APP需要使用录音, 请打开录音权限允许APP使用') } this.setState({ hasPermission: isAuthor }) // 录音进展 AudioRecorder.onProgress = (data) => { const duration = Math.ceil(data.currentTime); console.log("录音进度", duration) this.setState({ duration: duration }) if (duration >= 180) { this.handleStopAudio(); return toastShort("录音最长不超过3分钟") } }; }) }; // 停止录音 handleStopAudio = async () => { //如果已经关闭,那么不需要管 if (!this.state.isRecording) { return; } try { const { onRecordFinish } = this.props; const { audioPath, voiceFileName } = this.state; this.setState({ isRecording: false }) let nowTime = new Date().getTime(); if ((nowTime - this.recordStartTime) / 1000 < 1) { //录音时间太短、放弃此段录音 await AudioRecorder.stopRecording(); toastShort("录音时间太短,请您重试!"); return this.prepareRecordingPath(this.state.audioPath); } await AudioRecorder.stopRecording(); let voice = { audioPath: audioPath, duration: nowTime - this.recordStartTime, name: voiceFileName, recordEndDate: new Date().getTime() }; onRecordFinish && onRecordFinish(voice) // const storeVoiceFileUrl = RNFS.DocumentDirectoryPath + '/' + 'acc_voice/' + getCurrentDateNs() + getFileType(audioPath); // RNFS.copyFile(audioPath, storeVoiceFileUrl) // .then(res => { // console.log("音频复制结果", res, audioPath, storeVoiceFileUrl) // RNFS.exists(storeVoiceFileUrl) // .then(resE => { // console.log("resE", resE) // voice.audioPath = storeVoiceFileUrl; // onRecordFinish && onRecordFinish(voice) // }) // .catch(e => { // }) // }) // .catch(err => { // console.log("图片复制结果shibai", err) // }) } catch (error) { console.error(error); this.prepareRecordingPath(this.state.audioPath); return toastShort("录音失败,请您重试!"); }; this.handleHide(); } handleStopAudioWithoutFile = async () => { if (!this.state.isRecording) { return; }; this.setState({ isRecording: false }) await AudioRecorder.stopRecording(); console.log("已结束") } ///var/mobile/Containers/Data/Application/E27D1D82-736E-42E2-A6A2-FE1E715D6864/Documents/ ///var/mobile/Containers/Data/Application/E27D1D82-736E-42E2-A6A2-FE1E715D6864/Documents /** * AudioRecorder.prepareRecordingAtPath(path,option) * 录制路径 * path 路径 * option 参数 */ prepareRecordingPath = (path) => { const option = { SampleRate: 44100.0, //采样率 Channels: 2, //通道 AudioQuality: 'High', //音质 AudioEncoding: 'aac', //音频编码 aac OutputFormat: 'mpeg_4', //输出格式 MeteringEnabled: false, //是否计量 MeasurementMode: false, //测量模式 AudioEncodingBitRate: 32000, //音频编码比特率 IncludeBase64: true, //是否是base64格式 AudioSource: 0, //音频源 } this.setState({ audioPath: path }) //初始化当前录音的文件存放路径以及配置 AudioRecorder.prepareRecordingAtPath(path, option); } public showConfirmClose = () => { const { autoStart } = this.props; if (autoStart) { let confirmData = { title: "是否保存当前录音?", confirmText: "保存", confirmFun: this.handleStopAudio.bind(this), cancelFun: this.handleHide.bind(this) }; myConfirm(confirmData); } else { this.handleHide(); } }; public handleHide = () => { console.log("handleHide") this.sheetRef.snapTo(0); this.sheetRef.snapTo(0); const { onClose } = this.props; onClose && onClose(); this.delayHideTimer = setTimeout(() => { this._onCloseEnd(); }, 250); }; public show = (index?) => { //打开下拉框 const { autoStart = false } = this.props; let path = AudioUtils.DocumentDirectoryPath + `/quick_audio_${new Date().getTime()}.aac`; this.prepareRecordingPath(path) if (autoStart) { this.setState({ voiceFileName: "录音文件" }) this.handleStartAudio(); } else { if (isEmpty(index)) { this.setState({ voiceFileName: "新录音1" }) } else { this.setState({ voiceFileName: `新录音${index + 1}` }) } } Keyboard.dismiss(); this.delayHideTimer && clearTimeout(this.delayHideTimer); this.recordBtnIconRef && this.recordBtnIconRef.play(49, 50) this.sheetContainerRef.setNativeProps({ style: { display: 'flex', zIndex: 999 } }); this.sheetRef.snapTo(1); this.sheetRef.snapTo(1); }; public _onCloseEnd = () => { handleDismissKeyboard(); this.sheetContainerRef.setNativeProps({ style: { display: 'none', zIndex: -1 } }); this.setState({ duration: 0 }) if (this.state.isRecording) { this.handleStopAudioWithoutFile(); } }; calculatSheetHeight() { const { autoStart = false } = this.props; const { deviceHeight = 700 } = this.state; let callBackData = { sheetHeight: autoStart ? deviceHeight * 0.7 : deviceHeight, dargable: false } return callBackData }; // 开始录音 handleStartAudio = async () => { if (!this.state.hasPermission) { return alert('APP需要使用录音,请打开录音权限允许APP使用') } //this.prepareRecordingPath(this.state.audioPath); this.recordStartTime = new Date().getTime(); try { this.setState({ isRecording: true }) await AudioRecorder.startRecording() } catch (err) { console.error(err) } }; switchRecording() { const { isRecording } = this.state; if (isRecording) { //停止录音 this.recordBtnIconRef.play(150, 220); this.handleStopAudio(); } else { //开始录音 this.recordBtnIconRef.play(40, 120); this.handleStartAudio(); }; this.setState({ isRecording: !isRecording }) }; adaptDurationTime() { const { duration } = this.state; // console.log("duration------>", duration) let min = Math.floor(duration / 60); let sec = (duration % 60); if (min < 10) { //@ts-ignore min = '0' + min }; if (sec < 10) { //@ts-ignore sec = '0' + sec; } return `${min}:${sec}` } adaptLastDurationTime() { const { duration } = this.state; const lastTime = 60 - duration; if (lastTime <= 0) { this.handleStopAudio(); return toast("录音已达最长时间1分钟,自动为您结束录制") } let min = Math.floor(lastTime / 60); let sec = (lastTime % 60); if (min < 10) { //@ts-ignore min = '0' + min }; if (sec < 10) { //@ts-ignore sec = '0' + sec; } return `${min}:${sec}` } onVoiceFileNameChange(text) { this.setState({ voiceFileName: text }) } //50~120 开始录制 150 ~ 220 停止录制 renderInner() { const { isRecording, voiceFileName, deviceHeight } = this.state; const { sheetHeight, dargable } = this.calculatSheetHeight(); return ( this.sheetBoxRef = c} style={[styles.sheetBox]}> {this.adaptDurationTime()} { isRecording ? : null } this.recordBtnIconRef = c} autoPlay={false} loop={false} speed={2.4} style={{ width: px2dp(200), height: px2dp(200) }} source={require('./../../animated/record-voice-sheet-icon.json')} /> {/* @ts-ignore */} -{this.adaptLastDurationTime()} ) }; render() { const { isInTab = true } = this.props; //null safety const { sheetHeight, dargable } = this.calculatSheetHeight(); return ( this.sheetContainerRef = c} style={styles.sheetContainer}> {/* this.handleHide()} style={styles.touchOverlayContent}> */} { this.sheetRef = c }} borderRadius={px2dp(12)} onCloseEnd={this._onCloseEnd} /> ) } }; const styles = StyleSheet.create({ sheetContainer: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, height: '100%', width: '100%', display: 'none', zIndex: -1, // backgroundColor: 'red' }, sheetBoxContainer: { position: 'relative', width: '100%', // backgroundColor: 'red' }, sheetBox: { position: 'absolute', bottom: '0%', left: 0, height: '70%', width: '100%', alignItems: 'center', backgroundColor: '#fff', borderTopLeftRadius: px2dp(12), borderTopRightRadius: px2dp(12), paddingVertical: px2dp(12), paddingBottom: px2dp(36), }, touchOverlayContent: { width: '100%', height: '100%', }, overlay: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0,0.7)', // zIndex: 0 }, sheetheader: { width: '100%', height: px2dp(52), flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }, sheetheaderSide: { width: px2dp(42), height: '100%', justifyContent: 'center', alignItems: 'center' }, sheetContent: { flex: 1, width: '100%', justifyContent: 'space-between', alignItems: 'center' // backgroundColor: 'red' }, sheetTop: { justifyContent: 'flex-start', alignItems: 'center' }, sheetBottom: { width: '100%', justifyContent: 'flex-start', alignItems: 'center' }, recordBtn: { width: px2dp(60), height: px2dp(60), justifyContent: 'center', alignItems: 'center' }, bottomOptionRow: { width: '100%', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: px2dp(12.5) }, decBtn: { width: px2dp(170), height: px2dp(60), justifyContent: 'center', alignItems: 'center', // borderColor: "#d2d2d2", // borderWidth: onePx, }, optionLineIconContainer: { position: 'absolute', left: px2dp(12), top: 0, width: px2dp(52), height: px2dp(52), justifyContent: 'center', alignItems: 'center', }, optionLineIcon: { width: px2dp(18), height: px2dp(18), tintColor: colors.themeColor, }, optionLine: { position: 'relative', flexDirection: 'row', width: '100%', height: px2dp(52), justifyContent: 'center', alignItems: 'center', borderBottomColor: '#d2d2d2', borderBottomWidth: onePx, marginBottom: 1 }, voiceNameInput: { maxWidth: px2dp(180), fontSize: 18, color: '#333', textAlign: 'center', overflow: 'hidden', justifyContent: 'center', alignItems: 'center' }, timeText: { fontSize: 16, color: '#7f7f7f', marginTop: px2dp(6) } })