addVoice.js 8.17 KB
/**
 * Created by Cassie on 2018/05/14
 */
import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    Image,
    InteractionManager,
    NativeModules,
    ActivityIndicator,
    PermissionsAndroid
} from 'react-native';
import {AudioRecorder,AudioUtils} from 'react-native-audio';

import {zoomW,zoomH} from '../../utils/getSize';
import {xnToast,formatTime,NoDoublePress} from '../../utils/utils';
import AppService from "../../service/AppService";

const cancle = require('../../img/cancle.png');
const ok = require('../../img/ok.png');
const record = require('../../img/record.png');
const pauseRecord = require('../../img/pauseRecord.png');

export default class AddVoice extends Component {
    static navigationOptions = ({ navigation, screenProps }) => ({
        header:null
    });

    constructor(props){
        super(props);
        this.state = {
            seconds:0,
            currentTime:'00:00',
            recording:false,
            stoppedRecording:false,
            finished:false,
            audioPath:AudioUtils.DocumentDirectoryPath + '/test.aac',
            canRecord:true
        };
    };

    componentWillMount(){

    };

    componentDidMount(){
        AudioRecorder.prepareRecordingAtPath(this.state.audioPath,{
            SampleRate:22050,
            Channels:1,
            AudioQuality:"Low",
            AudioEncoding:"aac",
            AudioEncodingBitRate:32000
        });
        AudioRecorder.onProgress = (data) => {
            this.setState({
                seconds:data.currentTime,
                currentTime:formatTime(Math.floor(data.currentTime))
            });
        };
        AudioRecorder.onFinished = (data) => {
            if(__IOS__){
                this.uploadVoice(data.audioFileURL)
            }
        };
    };
    /*开始录音*/
    onRecord(){
        if(this.state.seconds == 0){
            AudioRecorder.startRecording();
        }else{
            AudioRecorder.resumeRecording();
        }
        this.setState({
            canRecord:false
        });
    };
    /*暂停录音*/
    async pauseRecord(){
        AudioRecorder.pauseRecording();
        this.setState({
            canRecord:true
        });
    };
    /*完成录音*/
    async doneRecord(){
        if(__IOS__){
            if(!this.state.canRecord){
                this.pauseRecord();
                if(this.state.seconds != 0){
                    AudioRecorder.stopRecording();
                }
            }else{
                if(this.state.seconds != 0){
                    AudioRecorder.stopRecording();
                }
            }
        }else{
            const filePath = await AudioRecorder.stopRecording();
            this.uploadVoice(filePath);
        }
    };
    /*上传录音*/
    uploadVoice(url){
        let fileName = Number(new Date())+'.aac';
        if(global.isConnected){
            this.setState({
                loading:true
            });
            AppService.getAccess({name:fileName}).then((res) => {
                if(res.message){
                    xnToast(res.message);
                    this.setState({
                        loading:false
                    });
                    return;
                }
                if(res.errors.length > 0) {
                    xnToast(res.errors[0].message);
                    this.setState({
                        loading:false
                    });
                }else{
                    NativeModules.system.simpleUpload(res.accessKeyId,res.accessKeySecret,res.securityToken,res.info.endpoint,res.info.bucket,fileName,url).then((response) => {
                        this.setState({
                            loading:false
                        });
                        let extension = response.substring(response.lastIndexOf('.')+1).toLowerCase();
                        let params = {
                            type:'VEDIO',
                            name:response.substring(response.lastIndexOf('/')+1,response.lastIndexOf('.')),
                            extension:extension,
                            storagePath:response,
                            sourceType:'DIRECT',
                            size:this.state.seconds
                        };
                        this.props.navigation.state.params.callback(params);
                        InteractionManager.runAfterInteractions(() => {this.props.navigation.goBack();})
                    }).catch((error) => {
                        this.setState({
                            loading:false
                        });
                        xnToast(error)
                    })
                }
            }).catch((error) => {
                this.setState({
                    loading:false
                });
                xnToast(error)
            })
        }else{
            xnToast('暂无网络连接,请稍后重试!')
        }
    };

    componentWillUnmount(){
        this.setState = (state,callback)=>{
            return;
        };
    };

    render(){
        return(
            <View style={styles.background}>
                <Text style={{fontSize:24,color:'#333',fontWeight:'bold',marginTop:(140/zoomH)}}>录音时间</Text>
                <Text style={{fontSize:48,color:'#00be3c',marginTop:(30/zoomH)}}>{this.state.currentTime}</Text>
                <View style={styles.videoSetting}>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => NoDoublePress.onPress(() => {InteractionManager.runAfterInteractions(() => {AudioRecorder.stopRecording();this.props.navigation.goBack();})})}>
                        <Image source={cancle} style={{width:(50/zoomH),height:(50/zoomH)}} resizeMode="contain" />
                    </TouchableOpacity>
                    {this.state.canRecord && <TouchableOpacity activeOpacity={0.8} onPress={() => NoDoublePress.onPress(() => {this.onRecord()})}>
                        <Image source={record} style={{width:(120/zoomH),height:(120/zoomH)}} />
                    </TouchableOpacity>}
                    {!this.state.canRecord && __IOS__ &&  <TouchableOpacity activeOpacity={0.8} onPress={() => NoDoublePress.onPress(() => {this.pauseRecord()})}>
                        <Image source={pauseRecord} style={{width:(120/zoomH),height:(120/zoomH)}} />
                    </TouchableOpacity>}
                    {!this.state.canRecord && __ANDROID__ &&  <TouchableOpacity activeOpacity={0.8} onPress={() => NoDoublePress.onPress(() => {this.pauseRecord()})}>
                        <Image source={pauseRecord} style={{width:(120/zoomH),height:(120/zoomH)}} />
                        <View style={{width:'100%',height:'100%',borderRadius:(60/zoomH),backgroundColor:'rgba(0,0,0,.2)',position:'absolute',top:0}} />
                    </TouchableOpacity>}
                    <TouchableOpacity activeOpacity={0.8} onPress={() => NoDoublePress.onPress(() => {this.doneRecord()})}>
                        <Image source={ok} style={{width:(50/zoomH),height:(50/zoomH)}} resizeMode="contain"/>
                    </TouchableOpacity>
                </View>
                {this.state.loading && <View style={styles.loadingBg}>
                    <View style={styles.loadingBox}>
                        <ActivityIndicator size='large' color='#fff' />
                        <Text style={{fontSize:16,color:'#fff',marginTop:(6/zoomH)}}>加载中...</Text>
                    </View>
                </View>}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    background:{
        flex:1,
        backgroundColor:'#fff',
        display:'flex',
        alignItems:'center'
    },
    videoSetting:{
        width:(300/zoomW),
        marginTop:(250/zoomH),
        display:'flex',
        flexDirection:'row',
        justifyContent:'space-between',
        alignItems:'center'
    },
    loadingBg:{
        position:'absolute',
        top:0,
        width:'100%',
        height:'100%',
        display:'flex',
        justifyContent:'center',
        alignItems:'center'
    },
    loadingBox:{
        width:(100/zoomW),
        height:(120/zoomH),
        backgroundColor:'rgba(0,0,0,.5)',
        borderRadius:8,
        display:'flex',
        alignItems:'center',
        justifyContent:'center'
    }
});