音频的录制逻辑(外部麦克风)

 #region 音频的录制逻辑
        private AudioClip mAudioClip;
        private int audioLength;
        private int maxRecordTime = 10;
        private int samplingRate = 12000;
        /// <summary>
        /// 开始录制视频时调用音频录制
        /// </summary>
        /// <returns></returns>
        public  bool TryStartRecording()
        {

            try
            {
                string[] micDevices = Microphone.devices;
                if (micDevices.Length == 0)
                {
                    UnityEngine.Debug.LogWarning("没有找到录音组件");

                }
                UnityEngine.Debug.LogWarning("####################111##@@@==>>  ");
                Microphone.End(null);
                mAudioClip = Microphone.Start(null, false, maxRecordTime, samplingRate);
                UnityEngine.Debug.LogWarning("####################111##@@@==>>  "+ mAudioClip);
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogWarning("####################22##@@@==>>  ");
                return false;
            }

            return true;
        }

        public  void EndRecording()
        {
            int lastPos = Microphone.GetPosition(null);

            if (Microphone.IsRecording(null))
            {
                audioLength = lastPos / samplingRate;
            }
            else
            {
                audioLength = maxRecordTime;
            }
            UnityEngine.Debug.LogWarning("####################22##@@@==>>  "+ mAudioClip+"  dsad ");
            Microphone.End(null);
            //UnityEngine.Debug.LogWarning("####################22##@@@==>>  ");
            //if (audioLength < 1.0f)
            //{
            //    mAudioClip = null;
            //    return;
            //}
        }


        public  byte[] GetData()
        {
            var data = new float[mAudioClip.samples * mAudioClip.channels];

            mAudioClip.GetData(data, 0);

            byte[] bytes = new byte[data.Length * 4];
            Buffer.BlockCopy(data, 0, bytes, 0, bytes.Length);

            return ConvertBytesZlib(bytes, CompressionMode.Compress);
        }

        public  byte[] ConvertBytesZlib(byte[] data, CompressionMode compressionMode)
        {
            CompressionMode mode = compressionMode;
            if (mode != CompressionMode.Compress)
            {
                if (mode != CompressionMode.Decompress)
                {
                    throw new NotImplementedException();
                }
                return ZlibStream.UncompressBuffer(data);
            }
            return ZlibStream.CompressBuffer(data);
        }
        #endregion

猜你喜欢

转载自blog.csdn.net/gtofei013/article/details/73878996