//根据byte数组,得到一个声音片段 public AudioClip BytesToAudioClip(byte[] buffer) { //byte数组和声音长度的换算 这里暂时不知道稳不稳定 float _nAudioTime = buffer.Length / ByteInLengthPropotion; //长度不难为0否则会报错 if (_nAudioTime <= 0.1f) { _nAudioTime = 0.1f; } //创建声音片段,取样大小==声音长度*频率 AudioClip clip = AudioClip.Create("AA", (int)(_nAudioTime * RecordFrequency), 1, RecordFrequency, false); //将_list反序列成完整的声音包列表 List <ViChatPacket> list = new List <ViChatPacket>(); int offest = 0; while (offest < buffer.Length) { ViChatPacket packet = ViChatPacketSerializer.DeSerializer(buffer, offest); offest = offest + 8 + packet.Data.Length; //8和包长度可能是这个声音包的包头 list.Add(packet); } int sampleIndex = 0; NSpeex.SpeexDecoder _speexDec = new NSpeex.SpeexDecoder(NSpeex.BandMode.Narrow); //解析器 for (int i = 0; i < list.Count; ++i) { //取反序列化的声音包 ViChatPacket iterPacket = list[i]; //包内数据拷贝到数组 byte[] sampleData = new byte[iterPacket.DataLength]; Buffer.BlockCopy(iterPacket.Data, 0, sampleData, 0, iterPacket.Length); //解压 float[] sample = ViSpeexCompress.DeCompress(_speexDec, sampleData, iterPacket.Length); //将数据添加到声音片段 clip.SetData(sample, sampleIndex); sampleIndex += sample.Length; } return(clip); }
public void PlayReconding(byte[] buffer, Action action = null) { audioSource.clip = AudioClip.Create("AA", 30 * 8000, 1, 8000, false); //byte[] buffer = _list.ToArray(); //Debug.Log("Length : " + buffer.Length.ToString()); List <ViChatPacket> list = new List <ViChatPacket>(); int offest = 0; while (offest < buffer.Length) { ViChatPacket packet = ViChatPacketSerializer.DeSerializer(buffer, offest); offest = offest + 8 + packet.Data.Length; list.Add(packet); } // int sampleIndex = 0; for (int iter = 0; iter < list.Count; ++iter) { ViChatPacket iterPacket = list[iter]; byte[] sampleData = new byte[iterPacket.DataLength]; Buffer.BlockCopy(iterPacket.Data, 0, sampleData, 0, iterPacket.Length); float[] sample = ViSpeexCompress.DeCompress(_speexDec, sampleData, iterPacket.Length); audioSource.clip.SetData(sample, sampleIndex); sampleIndex += sample.Length; } AudioManager.Instance.PlayEffectAudio(audioSource.clip, action); //audioSource.Play(); Debug.Log(audioSource.clip.length); //if (action != null) //{ // TimerMgr.instance.Subscribe(audioSource.clip.length * Time.timeScale, false, TimeEventType.IngoreTimeScale).OnComplete(delegate () // { // if (action != null) { action(); } // }); //} }