unity+录音(可更改时长,保存后时间长度和实际录音长度相同)

代码如下:

using UnityEngine;
using System.IO;
using System;
using UnityEngine.UI;
using System.Collections.Generic;
public class TKSoundRecord : MonoBehaviour {
    public static TKSoundRecord TKSoundRecordInstance;
    //public Image imageButton;
    //public Text TextPath;
    string filePath = null;
    string fileDefault = null;
    private AudioSource m_audioSource;
    private AudioClip m_audioClip;
    public AudioClip CurrentAudioClip;
    public const int SamplingRate = 8000;
    private const int HEADER_SIZE = 44;
 
    public bool isRecording = false;
    [HideInInspector]
    public Byte[] speech_Byte;
    //2018.10.18录音时长修改
    public float timer;
    public int SoundRecordTime =60;
    public bool isStartRecord = false;
    bool doOnce = false;
    bool endDoOnce = true;
    public String ShowRecordingState;
    public bool isSaveSoundSuccess;
    public List<AudioClip> CurrentSaveAudioList;
    public int soundID;

    //Max Voice input is 60s
    private const int TIME_FOR_TEMP_RECORD = 60;//可修改
    private const int FREQUENCY = 11025;
    private const float MIN_SECONDS = 0.0f;
    //private const int HEADER_SIZE = 44;

    private string _AudioName = "InputVoice";

    private bool _isCommandToRecord;
    public string m_strLastSavedPath;
    private AudioClip _myAudioClip;
    private AudioClip _completeAudioClip;
    public bool IsOneMinute;
    //public Text ShowRecordingStateText;
    private void Awake()
    {
        TKSoundRecordInstance = this;
    }
    // Use this for initialization
    void Start()
    {
        m_audioSource = GetComponent<AudioSource>();
        //filePath = Application.dataPath + "/StreamingAssets/";

        //filePath = Application.streamingAssetsPath;
        fileDefault = TKGlobalData.CurrentSaveDataPath ;
        //TextPath.text = filePath;
    }
    public void OnRecordingTimeLimit()
    {
        //ShowRecordingStateText.text = ShowRecordingState;
        if (isStartRecord)
        {
            timer += Time.deltaTime;
            //Debug.Log("timer+" + timer);
            if (timer >= TIME_FOR_TEMP_RECORD)
            {
                if (!doOnce)
                {
                    //Debug.Log("111");
                    doOnce = true;
                    EndRecording();
                }
            }
        }
        else
        {
            //if(!endDoOnce)
            //{
            //    Debug.LogError("222");
            //    endDoOnce=true;
            //    EndRecording();
            //}
            timer = 0;
        }
    }

    // Update is called once per frame
    void Update()
    {
        OnRecordingTimeLimit();
    }
    public void RecordStart()
    {
        if (Microphone.IsRecording(null))
        {
            Microphone.End(null);
            if (_myAudioClip != null)
            {
                _myAudioClip.UnloadAudioData();
                _myAudioClip = null;
            }
            _completeAudioClip = null;
        }
        _isCommandToRecord = true;
        _myAudioClip = Microphone.Start(null, false, TIME_FOR_TEMP_RECORD, FREQUENCY);
    }

    public void RecordStop()
    {
        _isCommandToRecord = false;
        Microphone.End(null);
        if (_myAudioClip != null)
        {
            _completeAudioClip = GetTransformAudioClip(_myAudioClip, MIN_SECONDS);
            _myAudioClip = null;
        }
    }

    public void Playrecord(AudioSource aue)
    {
        if (_completeAudioClip != null)
        {
            aue.clip = _completeAudioClip;
            aue.Play();
        }
    }

    private AudioClip GetTransformAudioClip(AudioClip srcAudioClip, float minSecond)
    {
        var samples = new float[srcAudioClip.samples];
        srcAudioClip.GetData(samples, 0);


        return GetTransformAudioClip(new List<float>(samples), minSecond, srcAudioClip.channels, srcAudioClip.frequency);
    }

    private AudioClip GetTransformAudioClip(List<float> samples, float min, int channels, int hz)
    {
        return GetTransformAudioClip(samples, min, channels, hz, false, false);
    }

    private AudioClip GetTransformAudioClip(List<float> samples, float min, int channels, int hz, bool _3D, bool stream)
    {
        int i;
        bool isLessMin = true;
        for (i = 0; i < samples.Count; i++)
        {
            if (Mathf.Abs(samples[i]) > min)
            {
                isLessMin = false;
                break;
            }
        }
        // less than the min seconds, so can't get the audio clip
        if (isLessMin)
            return null;
        if (samples.Count > i)
        {
            samples.RemoveRange(0, i);
        }

        if (samples.Count > i)
        {
            samples.RemoveRange(0, i);
        }
        for (i = samples.Count - 1; i > 0; i--)
        {
            if (Mathf.Abs(samples[i]) > min)
            {
                break;
            }
        }

        if (samples.Count > (samples.Count - i))
        {
            samples.RemoveRange(i, samples.Count - i);
        }

        var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
        clip.SetData(samples.ToArray(), 0);


        return clip;
    }

    public void SaveWavFile(string wavName, AudioClip clip, string savePath)
    {

        string filename = wavName;
        if (!filename.ToLower().EndsWith(".wav"))
        {
            filename += ".wav";
        }

        var filepath = Path.Combine(fileDefault,savePath+"/"+ filename);
        //Debug.LogError("filepath "+filepath);
        Directory.CreateDirectory(Path.GetDirectoryName(filepath));

        using (var fileStream = CreateEmptyNew(filepath))
        {
            ConvertAndWriteNew(fileStream, _completeAudioClip);
            WriteHeaderNew(fileStream, _completeAudioClip);
            CurrentAudioClip = clip;
            if (isSaveSoundSuccess)
            {
                CurrentSaveAudioList.Add(clip);
            }
        }
    }

    private FileStream CreateEmptyNew(string filepath)
    {
        if (File.Exists(filepath))
        {
            File.Delete(filepath);
        }
        var fileStream = new FileStream(filepath, FileMode.Create);
        byte emptyByte = new byte();
        for (int i = 0; i < HEADER_SIZE; i++) //preparing the header
        {
            fileStream.WriteByte(emptyByte);
        }
        return fileStream;
    }
    public MemoryStream GetAudioStream()
    {
        //byte[] arr = File.ReadAllBytes(path);

        MemoryStream stream = new MemoryStream();
        byte emptyByte = new byte();

        for (int i = 0; i < HEADER_SIZE; i++)
        {
            stream.WriteByte(emptyByte);
            if (_completeAudioClip != null)
            {
                ConvertAndWriteNew(stream, _completeAudioClip);
                WriteHeaderNew(stream, _completeAudioClip);
            }
        }
        return stream;
    }
    private void ConvertAndWriteNew(MemoryStream stream, AudioClip clip)
    {
        var samples = new float[clip.samples];
        clip.GetData(samples, 0);

        Int16[] intData = new Int16[samples.Length];

        Byte[] bytesData = new byte[samples.Length * 2];

        float rescaleFactor = 32767;

        for (int i = 0; i < samples.Length; i++)
        {
            intData[i] = (short)(samples[i] * rescaleFactor);
            Byte[] byteArr = new Byte[2];
            byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }
        stream.Write(bytesData, 0, bytesData.Length);
    }

    private void WriteHeaderNew(FileStream stream, AudioClip clip)
    {
        var hz = clip.frequency;
        var channels = clip.channels;
        var samples = clip.samples;

        stream.Seek(0, SeekOrigin.Begin);
        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
        stream.Write(riff, 0, 4);

        Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8);
        stream.Write(chunkSize, 0, 4);

        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
        stream.Write(wave, 0, 4);

        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
        stream.Write(fmt, 0, 4);

        Byte[] subChunk1 = BitConverter.GetBytes(16);
        stream.Write(subChunk1, 0, 4);

        UInt16 two = 2;
        UInt16 one = 1;

        Byte[] audioFormat = BitConverter.GetBytes(one);
        stream.Write(audioFormat, 0, 2);

        Byte[] numChannels = BitConverter.GetBytes(channels);
        stream.Write(numChannels, 0, 2);

        Byte[] sampleRate = BitConverter.GetBytes(hz);
        stream.Write(sampleRate, 0, 4);

        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
        stream.Write(byteRate, 0, 4);

        UInt16 blockAlign = (ushort)(channels * 2);
        stream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

        UInt16 bps = 16;
        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
        stream.Write(bitsPerSample, 0, 2);

        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
        stream.Write(datastring, 0, 4);

        Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
        stream.Write(subChunk2, 0, 4);
    }

    private void ConvertAndWriteNew(FileStream stream, AudioClip clip)
    {
        var samples = new float[clip.samples];
        clip.GetData(samples, 0);

        Int16[] intData = new Int16[samples.Length];

        Byte[] bytesData = new byte[samples.Length * 2];

        float rescaleFactor = 32767;

        for (int i = 0; i < samples.Length; i++)
        {
            intData[i] = (short)(samples[i] * rescaleFactor);
            Byte[] byteArr = new Byte[2];
            byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }
        stream.Write(bytesData, 0, bytesData.Length);
    }

    private void WriteHeaderNew(MemoryStream stream, AudioClip clip)
    {
        var hz = clip.frequency;
        var channels = clip.channels;
        var samples = clip.samples;

        stream.Seek(0, SeekOrigin.Begin);
        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
        stream.Write(riff, 0, 4);

        Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8);
        stream.Write(chunkSize, 0, 4);

        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
        stream.Write(wave, 0, 4);

        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
        stream.Write(fmt, 0, 4);

        Byte[] subChunk1 = BitConverter.GetBytes(16);
        stream.Write(subChunk1, 0, 4);

        UInt16 two = 2;
        UInt16 one = 1;

        Byte[] audioFormat = BitConverter.GetBytes(one);
        stream.Write(audioFormat, 0, 2);

        Byte[] numChannels = BitConverter.GetBytes(channels);
        stream.Write(numChannels, 0, 2);

        Byte[] sampleRate = BitConverter.GetBytes(hz);
        stream.Write(sampleRate, 0, 4);

        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
        stream.Write(byteRate, 0, 4);

        UInt16 blockAlign = (ushort)(channels * 2);
        stream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

        UInt16 bps = 16;
        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
        stream.Write(bitsPerSample, 0, 2);

        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
        stream.Write(datastring, 0, 4);

        Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
        stream.Write(subChunk2, 0, 4);

        stream.Close();
    }







    public void StartRecording()
    {
        isStartRecord = true;
        doOnce = false;
        RecordStart();//2019.6.12
        //Microphone.End(null);
        //foreach (string d in Microphone.devices)
        //{
        //    Debug.Log("Devid :" + d);
        //}
        ////m_audioClip = Microphone.Start(null, false, SoundRecordTime, SamplingRate);
        //m_audioClip = Microphone.Start(null, false, TIME_FOR_TEMP_RECORD, FREQUENCY);
        ////imageButton.color = Color.red;
        ////Debug.Log("@@@@Microphone.IsRecording(null)" + Microphone.IsRecording(null));
        ShowRecordingState = "开始录制!";
    }
    public void EndRecording()
    {
        isStartRecord = false;
        //imageButton.color = Color.blue;
        int audioLength = 0;
        int lastPos = Microphone.GetPosition(null);
        //Debug.Log("Microphone.IsRecording(null)" + Microphone.IsRecording(null));
        if (Microphone.IsRecording(null))
        {
            audioLength = lastPos / FREQUENCY;
        }
        else
        {
            audioLength = 1;
            Debug.Log("error : 录音时间太短");
        }
        //Microphone.End(null);//2019.6.12
        //Debug.Log("audioLength" + audioLength);
        if (audioLength <= 1.0f)
        {
            //Debug.Log("录音时间小于1s,请重新录制");
            ShowRecordingState = "录音时间小于1s,请重新录制";
            isSaveSoundSuccess = false;
            IsOneMinute = false;
            return;
        }
        //ShowRecordingState = "暂停录制!";
        ShowRecordingState = "保存成功";
        IsOneMinute = true;
        soundID++;// 2019.6.13
        isSaveSoundSuccess = true;
        RecordStop();//2019.6.12
       // bool Res = SaveWav("Microphone", m_audioClip);
    }
    public void PlayAudioClip()
    {
        if (m_audioClip.length > 5 && m_audioClip != null)
        {
            if (m_audioSource.isPlaying)
            {
                m_audioSource.Stop();
            }
            Debug.Log("Channel :" + m_audioClip.channels + " ;Samle :" + m_audioClip.samples + " ;frequency :" + m_audioClip.frequency + " ;length :" + m_audioClip.length);
            m_audioSource.clip = m_audioClip;
            m_audioSource.Play();
            Playrecord(m_audioSource);
        }
    }
    public void OnSaveWav(string wavName,string savePath)
    {
        //SaveWav(wavName+soundID,m_audioClip,savePath);
        
        SaveWavFile(wavName + soundID, _completeAudioClip, savePath);
    }
    public void OnSaveWavProgrem( string wavName, string savePath)
    {
        //SaveWav(wavName+soundID,m_audioClip,savePath);
      
        SaveWavFile(wavName, _completeAudioClip, savePath);
    }
    bool SaveWav(string filename, AudioClip clip,string savePatn)
    {
        try
        {
            if (!filename.ToLower().EndsWith(".wav"))
            {
                filename += ".wav";
            }
            var  filePath = Path.Combine( fileDefault , savePatn + "/" + filename);

            //Debug.Log("Record Ok :" + filePath);

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }

            using (var fileStream = CreateEmpty(filePath))
            {
                ConvertAndWrite(fileStream, clip);
                CurrentAudioClip = clip;
                //Debug.LogError(clip.name);
                if (isSaveSoundSuccess)
                {
                    CurrentSaveAudioList.Add(clip);
                }
                //ShowRecordingState = "保存成功!";
                //Debug.LogError("baocnchengg");
            }
            //Debug.LogError(filePath);
            return true;
        }
        catch (Exception ex)
        {
            Debug.Log("error : " + ex);
            return false;
        }
        //try
        //{
        //    if (!filename.ToLower().EndsWith(".wav"))
        //    {
        //        filename += ".wav";
        //    }

        //    filePath = fileDefault +savePatn+"/"+ filename;

        //    //Debug.Log("Record Ok :" + filePath);

        //    if (!Directory.Exists(filePath))
        //    {
        //        Directory.CreateDirectory(Path.GetDirectoryName(filePath));
        //    }
        //    using (FileStream fileStream = CreateEmpty(filePath))
        //    {
        //        ConvertAndWrite(fileStream, clip);
        //        CurrentAudioClip=clip;
        //        //Debug.LogError(clip.name);
        //        if (isSaveSoundSuccess)
        //        {
        //            CurrentSaveAudioList.Add(clip);
        //        }
        //        //ShowRecordingState = "保存成功!";
        //        //Debug.LogError("baocnchengg");
        //    }
        //    //Debug.LogError(filePath);
        //    return true;
        //}
        //catch (Exception ex)
        //{
        //    Debug.Log("error : " + ex);
        //    return false;
        //}

    }

    FileStream CreateEmpty(string filePath)
    {
        FileStream fileStream = new FileStream(filePath, FileMode.Create);
        byte emptyByte = new byte();

        for (int i = 0; i < HEADER_SIZE; i++)
        {
            fileStream.WriteByte(emptyByte);
        }
        return fileStream;
    }
    void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    {
        var samples = new float[clip.samples];
        clip.GetData(samples, 0);

        Int16[] intData = new Int16[samples.Length];

        Byte[] bytesData = new byte[samples.Length * 2];

        float rescaleFactor = 32767;

        for (int i = 0; i < samples.Length; i++)
        {
            intData[i] = (short)(samples[i] * rescaleFactor);
            Byte[] byteArr = new Byte[2];
            byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }
        speech_Byte = bytesData;
        fileStream.Write(bytesData, 0, bytesData.Length);
        WriteHeader(fileStream, clip);
        //float[] samples = new float[clip.samples];

        //clip.GetData(samples, 0);

        //Int16[] intData = new Int16[samples.Length];

        //Byte[] bytesData = new Byte[samples.Length * 2];

        //int rescaleFactor = 32767; //to convert float to Int16

        //for (int i = 0; i < samples.Length; i++)
        //{
        //    intData[i] = (short)(samples[i] * rescaleFactor);

        //    Byte[] byteArr = new Byte[2];
        //    byteArr = BitConverter.GetBytes(intData[i]);
        //    byteArr.CopyTo(bytesData, i * 2);
        //}

        //speech_Byte = bytesData;
        ////Debug.LogError("speech_Byte**"+ speech_Byte);
        //fileStream.Write(bytesData, 0, bytesData.Length);

        //WriteHeader(fileStream, clip);
    }
    void WriteHeader(FileStream stream, AudioClip clip)
    {

        var hz = clip.frequency;
        var channels = clip.channels;
        var samples = clip.samples;

        stream.Seek(0, SeekOrigin.Begin);
        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
        stream.Write(riff, 0, 4);

        Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8);
        stream.Write(chunkSize, 0, 4);

        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
        stream.Write(wave, 0, 4);

        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
        stream.Write(fmt, 0, 4);

        Byte[] subChunk1 = BitConverter.GetBytes(16);
        stream.Write(subChunk1, 0, 4);

        UInt16 two = 2;
        UInt16 one = 1;

        Byte[] audioFormat = BitConverter.GetBytes(one);
        stream.Write(audioFormat, 0, 2);

        Byte[] numChannels = BitConverter.GetBytes(channels);
        stream.Write(numChannels, 0, 2);

        Byte[] sampleRate = BitConverter.GetBytes(hz);
        stream.Write(sampleRate, 0, 4);

        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
        stream.Write(byteRate, 0, 4);

        UInt16 blockAlign = (ushort)(channels * 2);
        stream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

        UInt16 bps = 16;
        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
        stream.Write(bitsPerSample, 0, 2);

        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
        stream.Write(datastring, 0, 4);

        Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
        stream.Write(subChunk2, 0, 4);

        stream.Close();
    }

}

//using UnityEngine;
//using System.IO;
//using System;
//using UnityEngine.UI;
//using System.Collections.Generic;
//public class TKSoundRecord : MonoBehaviour
//{
//    public static TKSoundRecord TKSoundRecordInstance;
//    //public Image imageButton;
//    //public Text TextPath;
//    string filePath = null;
//    string fileDefault = null;
//    private AudioSource m_audioSource;
//    private AudioClip m_audioClip;
//    public AudioClip CurrentAudioClip;
//    public const int SamplingRate = 8000;
//    private const int HEADER_SIZE = 44;
//    private const int FREQUENCY = 11025;
//    public bool isRecording = false;
//    [HideInInspector]
//    public Byte[] speech_Byte;
//    //2018.10.18录音时长修改
//    public float timer;
//    public int SoundRecordTime = 60;
//    public bool isStartRecord = false;
//    bool doOnce = false;
//    bool endDoOnce = true;
//    public String ShowRecordingState;
//    public bool isSaveSoundSuccess;
//    public List<AudioClip> CurrentSaveAudioList;
//    public int soundID;
//    //public Text ShowRecordingStateText;
//    private void Awake()
//    {
//        TKSoundRecordInstance = this;
//    }
//    // Use this for initialization
//    void Start()
//    {
//        m_audioSource = GetComponent<AudioSource>();
//        //filePath = Application.dataPath + "/StreamingAssets/";

//        //filePath = Application.streamingAssetsPath;
//        fileDefault = TKGlobalData.CurrentSaveDataPath;
//        //TextPath.text = filePath;
//    }
//    public void OnRecordingTimeLimit()
//    {
//        //ShowRecordingStateText.text = ShowRecordingState;
//        if (isStartRecord)
//        {
//            timer += Time.deltaTime;
//            //Debug.Log("timer+" + timer);
//            if (timer >= SoundRecordTime)
//            {
//                if (!doOnce)
//                {
//                    //Debug.Log("111");
//                    doOnce = true;
//                    EndRecording();
//                }

//            }
//        }
//        else
//        {
//            //if(!endDoOnce)
//            //{
//            //    Debug.LogError("222");
//            //    endDoOnce=true;
//            //    EndRecording();
//            //}

//            timer = 0;
//        }
//    }

//    // Update is called once per frame
//    void Update()
//    {
//        OnRecordingTimeLimit();
//    }

//    public void StartRecording()
//    {

//        isStartRecord = true;
//        doOnce = false;
//        Microphone.End(null);
//        foreach (string d in Microphone.devices)
//        {
//            Debug.Log("Devid :" + d);
//        }
//        //m_audioClip = Microphone.Start(null, false, SoundRecordTime, SamplingRate);
//        m_audioClip = Microphone.Start(null, false, SoundRecordTime, FREQUENCY);
//        //imageButton.color = Color.red;
//        //Debug.Log("@@@@Microphone.IsRecording(null)" + Microphone.IsRecording(null));
//        ShowRecordingState = "开始录制!";

//    }
//    public void EndRecording()
//    {
//        isStartRecord = false;

//        //imageButton.color = Color.blue;

//        int audioLength = 0;
//        int lastPos = Microphone.GetPosition(null);
//        //Debug.Log("Microphone.IsRecording(null)" + Microphone.IsRecording(null));
//        if (Microphone.IsRecording(null))
//        {
//            audioLength = lastPos / SamplingRate;
//        }
//        else
//        {
//            audioLength = 1;
//            Debug.Log("error : 录音时间太短");
//        }
//        Microphone.End(null);

//        Debug.Log("audioLength" + audioLength);

//        if (audioLength <= 1.0f)
//        {
//            Debug.Log("录音时间小于1s,请重新录制");
//            ShowRecordingState = "录音时间小于1s,请重新录制";
//            isSaveSoundSuccess = false;
//            return;
//        }
//        //ShowRecordingState = "暂停录制!";
//        ShowRecordingState = "保存成功";
//        soundID++;
//        isSaveSoundSuccess = true;
//        // bool Res = SaveWav("Microphone", m_audioClip);
//    }
//    public void PlayAudioClip()
//    {
//        if (m_audioClip.length > 5 && m_audioClip != null)
//        {
//            if (m_audioSource.isPlaying)
//            {
//                m_audioSource.Stop();
//            }
//            Debug.Log("Channel :" + m_audioClip.channels + " ;Samle :" + m_audioClip.samples + " ;frequency :" + m_audioClip.frequency + " ;length :" + m_audioClip.length);
//            m_audioSource.clip = m_audioClip;
//            m_audioSource.Play();
//        }
//    }
//    public void OnSaveWav(string wavName, string savePath)
//    {
//        SaveWav(wavName + soundID, m_audioClip, savePath);
//    }

//    bool SaveWav(string filename, AudioClip clip, string savePatn)
//    {
//        try
//        {
//            if (!filename.ToLower().EndsWith(".wav"))
//            {
//                filename += ".wav";
//            }

//            filePath = fileDefault + savePatn + "/" + filename;

//            //Debug.Log("Record Ok :" + filePath);

//            if (!Directory.Exists(filePath))
//            {
//                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
//            }
//            using (FileStream fileStream = CreateEmpty(filePath))
//            {
//                ConvertAndWrite(fileStream, clip);
//                CurrentAudioClip = clip;
//                //Debug.LogError(clip.name);
//                if (isSaveSoundSuccess)
//                {
//                    CurrentSaveAudioList.Add(clip);
//                }
//                //ShowRecordingState = "保存成功!";
//                //Debug.LogError("baocnchengg");
//            }
//            //Debug.LogError(filePath);
//            return true;
//        }
//        catch (Exception ex)
//        {
//            Debug.Log("error : " + ex);
//            return false;
//        }

//    }

//    FileStream CreateEmpty(string filePath)
//    {
//        FileStream fileStream = new FileStream(filePath, FileMode.Create);
//        byte emptyByte = new byte();

//        for (int i = 0; i < HEADER_SIZE; i++)
//        {
//            fileStream.WriteByte(emptyByte);
//        }
//        return fileStream;
//    }
//    void ConvertAndWrite(FileStream fileStream, AudioClip clip)
//    {
//        float[] samples = new float[clip.samples];

//        clip.GetData(samples, 0);

//        Int16[] intData = new Int16[samples.Length];

//        Byte[] bytesData = new Byte[samples.Length * 2];

//        int rescaleFactor = 32767; //to convert float to Int16

//        for (int i = 0; i < samples.Length; i++)
//        {
//            intData[i] = (short)(samples[i] * rescaleFactor);

//            Byte[] byteArr = new Byte[2];
//            byteArr = BitConverter.GetBytes(intData[i]);
//            byteArr.CopyTo(bytesData, i * 2);
//        }

//        speech_Byte = bytesData;
//        //Debug.LogError("speech_Byte**"+ speech_Byte);
//        fileStream.Write(bytesData, 0, bytesData.Length);

//        WriteHeader(fileStream, clip);
//    }
//    void WriteHeader(FileStream fileStream, AudioClip clip)
//    {

//        int hz = clip.frequency;
//        int channels = clip.channels;
//        int samples = clip.samples;

//        fileStream.Seek(0, SeekOrigin.Begin);

//        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
//        fileStream.Write(riff, 0, 4);

//        Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
//        fileStream.Write(chunkSize, 0, 4);

//        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
//        fileStream.Write(wave, 0, 4);

//        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
//        fileStream.Write(fmt, 0, 4);

//        Byte[] subChunk1 = BitConverter.GetBytes(16);
//        fileStream.Write(subChunk1, 0, 4);

//        UInt16 two = 2;
//        UInt16 one = 1;

//        Byte[] audioFormat = BitConverter.GetBytes(one);
//        fileStream.Write(audioFormat, 0, 2);

//        Byte[] numChannels = BitConverter.GetBytes(channels);
//        fileStream.Write(numChannels, 0, 2);

//        Byte[] sampleRate = BitConverter.GetBytes(hz);
//        fileStream.Write(sampleRate, 0, 4);

//        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2); // sampleRate * bytesPerSample*number of channels, here 44100*2*2  
//        fileStream.Write(byteRate, 0, 4);

//        UInt16 blockAlign = (ushort)(channels * 2);
//        fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

//        UInt16 bps = 16;
//        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
//        fileStream.Write(bitsPerSample, 0, 2);

//        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
//        fileStream.Write(datastring, 0, 4);

//        Byte[] subChunk2 = BitConverter.GetBytes(samples * 2 * channels);
//        fileStream.Write(subChunk2, 0, 4);

//        fileStream.Close();
//        //Debug.Log(" OK ");
//    }

//}

  调用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class TKSoundRecordManager : TKUIManager
{
    public Button ReturnButton;
    public Button SaveButton;
    public Button SoundRecordButton;
    public Text SoundRecordTipText;
    public Text DeviceNameText;
    //
    private GameObject soundPlayObj;
    //private Toggle Toggle_palyOrPasueSoundItem;
    public List<GameObject> createSoundItemList;
    public RectTransform SoundContentParent;
    public Sprite[] PlaySoundSprite;
    public List<AudioClip> AudioClipList;
    public AudioSource CurrentAudioSource;
    public Dictionary<GameObject, AudioClip> AudioClipDic;
   
    private void Awake()
    {
       OnInit();
     DeviceNameText.text= TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiName;
    }
    private void OnEnable()
    {
        if (CurrentAudioSource.isPlaying)
        {
            CurrentAudioSource.Stop();
        }
        foreach (var item in createSoundItemList)
        {
            item.transform.GetChild(1).GetComponent<Toggle>().isOn = false;
            item.transform.GetChild(1).GetComponent<Toggle>().transform.GetChild(0).GetComponent<Image>().sprite = PlaySoundSprite[1];
            //item.transform.GetChild(1).GetComponent<Toggle>().isOn = false;
        }
        TKSoundRecord.TKSoundRecordInstance.ShowRecordingState = "";
    }
    // Use this for initialization
    void Start ()
    {
        CurrentAudioSource = gameObject.GetComponent<AudioSource>();
        TKSoundRecord.TKSoundRecordInstance.ShowRecordingState = "";
        AudioClipDic = new Dictionary<GameObject, AudioClip>();
      
    }
   
	// Update is called once per frame
	void Update ()
    {
        SoundRecordTipText.text = TKSoundRecord.TKSoundRecordInstance.ShowRecordingState;
	}
    public override void OnInit()
    {
        OnBindEvent();

    }
    public override void OnBindEvent()
    {
        base.OnBindEvent();
        EventTriggerListener.Get(ReturnButton.gameObject).onClick += OnReturnButtonClick;
        //EventTriggerListener.Get(SaveButton.gameObject).onClick += OnSaveButtonClick;
        SaveButton.onClick.AddListener(delegate () { OnSaveButtonClick(SaveButton.gameObject); });
        //SoundRecordButton按下是录音开始
        EventTriggerListener.Get(SoundRecordButton.gameObject).onDown += OnSoundRecordButtonClick;
        //SoundRecordButton抬起是录音结束
        EventTriggerListener.Get(SoundRecordButton.gameObject).onUp += OnSoundRecordEndButtonClick;

    }
    private void OnReturnButtonClick(GameObject go)
    {
        if (go == ReturnButton.gameObject)
        {
            OnReturnButton();
        }
    }
    private void OnReturnButton()
    {
        // Debug.Log("ReturnButton......");
        gameObject.SetActive(false);
        TKUIStateSelect.TKUIStateSelectInstance.OnSetCurrentUiPanelsState(TKPanelType.DeviceInformationPanel);
        TKUIStateSelect.TKUIStateSelectInstance.OnSetCurrentUiPanelsState(TKPanelType.DeviceInformationPanelParent);
    }
    private void OnSaveButtonClick(GameObject go)
    {
        if (go == SaveButton.gameObject)
        {
            OnSaveButton();
        }
    }
    int soundID = 0;
    private void OnSaveButton()
    {
       // Debug.Log("SaveButton......");
        soundID++;
        TKSoundRecord.TKSoundRecordInstance.OnSaveWav(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[0].equiId+"_",TKDataHandle.TKDataHandleInstance.CurrentWorkShops[0].workShopName);
    }
   
    //录音开始
    private void OnSoundRecordButtonClick(GameObject go)
    {
        if (go == SoundRecordButton.gameObject)
        {
            OnSoundRecordButton();
        }
    }
    private void OnSoundRecordButton()
    {
       // Debug.Log("SoundRecordButton......");
        TKSoundRecord.TKSoundRecordInstance.StartRecording();
    }
    //录音结束
    private void OnSoundRecordEndButtonClick(GameObject go)
    {
        if (go == SoundRecordButton.gameObject)
        {
            OnSoundRecordEndButton();
        }
    }
    IEnumerator AudioPlayFinished(float time, GameObject currentClickObj)
    {
        yield return new WaitForSeconds(time );
		currentClickObj.transform.GetChild(1).GetComponent<Toggle>().transform.GetChild(0).GetComponent<Image>().sprite = PlaySoundSprite[1];
    }
    
    private void playAudioSoundList(GameObject currentClickObj)
    {
        if (CurrentAudioSource.isPlaying)
        {
            CurrentAudioSource.Stop();
        }
      
        CurrentAudioSource.clip =currentClickObj.GetComponent<TKSoundItem>().currentSoundItemAudioClip;
        CurrentAudioSource.Play();
        StartCoroutine( AudioPlayFinished( CurrentAudioSource.clip.length, currentClickObj));
       //currentClickObj.transform.GetChild(1).GetComponent<Toggle>().transform.GetChild(0).GetComponent<Image>().sprite = PlaySoundSprite[1];
     
        //if (CurrentAudioSource.isPlaying)
        //      {
        //         CurrentAudioSource.Stop();
        //      }
        //      CurrentAudioSource.clip =audioClipItem;
        //      CurrentAudioSource.Play();
        //if (AudioClipList.Count != 0 && soundIdItem < AudioClipList.Count)
        //{
        //    if (AudioClipList[soundIdItem].length > 5 && AudioClipList[soundIdItem] != null)
        //    {
        //        if (CurrentAudioSource.isPlaying)
        //        {
        //            CurrentAudioSource.Stop();
        //        }
        //        Debug.LogError(soundIdItem);
        //        CurrentAudioSource.clip = AudioClipList[soundIdItem];
        //        CurrentAudioSource.Play();
        //    }
        //}

        //if(AudioClipDic.Count>0)
        //  {
        //      if (AudioClipDic.ContainsKey(currentClickObj))
        //      {
        //          if (CurrentAudioSource.isPlaying)
        //          {
        //              CurrentAudioSource.Stop();
        //          }
        //          CurrentAudioSource.clip = AudioClipDic[currentClickObj];
        //          CurrentAudioSource.Play();
        //      }
        //  }

    }
    private void PauseAudioSoundList(GameObject currentClickObj)
    {
		 if (CurrentAudioSource.isPlaying)
         {
            CurrentAudioSource.Stop();
         }
        CurrentAudioSource.clip =currentClickObj.GetComponent<TKSoundItem>().currentSoundItemAudioClip;
        CurrentAudioSource.Stop();
        //if(soundIdItem<AudioClipList.Count)
        //{
        //    if (AudioClipList[soundIdItem].length > 5 && AudioClipList[soundIdItem] != null)
        //    {
        //        if (CurrentAudioSource.isPlaying)
        //        {
        //            CurrentAudioSource.Stop();
        //        }
        //        CurrentAudioSource.clip = AudioClipList[soundIdItem];
        //        CurrentAudioSource.Stop();  
        //    }
        //}
		 //if(AudioClipDic.Count>0)
   //     {
   //         if (AudioClipDic.ContainsKey(currentClickObj))
   //         {
   //             if (CurrentAudioSource.isPlaying)
   //             {
   //                 CurrentAudioSource.Stop();
   //             }
   //             CurrentAudioSource.clip = AudioClipDic[currentClickObj];
   //             CurrentAudioSource.Stop();
   //         }
   //     }

    }
    private void OnSoundRecordEndButton()
    {
        //Debug.Log("SoundRecordEndButton......");
        
        TKSoundRecord.TKSoundRecordInstance.EndRecording();
        //soundID++;
        if (TKSoundRecord.TKSoundRecordInstance.isSaveSoundSuccess)
        {
            TKSoundRecord.TKSoundRecordInstance.OnSaveWav(TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiId + "_" + TKSoundRecord.TKSoundRecordInstance.soundID, TKDataHandle.TKDataHandleInstance.CurrentWorkShops[TKGlobalData.currentSelectWorkShopID].workShopName);

            //AudioClipList.Add(TKSoundRecord.TKSoundRecordInstance.CurrentAudioClip);
            OnCreateProjectContent("SoundItem", SoundContentParent);
        }
    }
    private void OnCreateProjectContent(string ObjName, RectTransform pathButtonPool)
    {
     
        //Debug.LogError("s" );
        //pathButtonPool.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 60, PuAnGetBrowserPathData.PuAnGetBrowserPathDataInstance.BrowserDataResules.Count * 65);//动态设置面板的长度2019.1.3
        pathButtonPool.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 10 * 65);//动态设置面板的长度2019.1.3
        //for (int i = 0; i < AudioClipList.Count; i++)
            //for (int i=0;i<AudioClipDic.Count;i++)
            {
            string txtName = TKDataHandle.TKDataHandleInstance.CurrentEquiInfos[TKGlobalData.currentSelectEquiID].equiName + "_"+TKSoundRecord.TKSoundRecordInstance.soundID ;
            //int currentVisitTitleIDSSS = i;
                //生成按钮对象,给位置,给名字,给点击事件
               var soundPlayObj = OnCreateButton(ObjName, pathButtonPool);
                //soundPlayObj.transform.localPosition = new Vector3(-20, (pathButtonPool.transform.localPosition.y + 50) - 100f * (1 + 1), 0);
                var Toggle_palyOrPasueSoundItem = soundPlayObj.transform.GetChild(1).GetComponent<Toggle>();
                soundPlayObj.transform.GetChild(1).transform.GetChild(1).GetComponent<Text>().text = txtName;
                //Debug.LogError("i***" + currentVisitTitleIDSSS+btn_CreateProjectItem.name);
                var clickButtonItemm=Toggle_palyOrPasueSoundItem.transform.GetChild(0).GetComponent<Button>();
                var deleteButtonItem = soundPlayObj.transform.GetChild(2).GetComponent<Button>();
				 //if (!AudioClipDic.ContainsKey(soundPlayObj))
     //           {
     //               AudioClipDic.Add(soundPlayObj, TKSoundRecord.TKSoundRecordInstance.CurrentAudioClip);
     //           }
                //Toggle_palyOrPasueSoundItem.onClick.AddListener(delegate () { this.OnToggle_playOrPasueSoundItemClick(Toggle_palyOrPasueSoundItem,soundID); });
                Toggle_palyOrPasueSoundItem.onValueChanged.AddListener((bool value) => OnToggle_playOrPasueSoundItemClick(Toggle_palyOrPasueSoundItem, value,clickButtonItemm,soundPlayObj));
            //Toggle_palyOrPasueSoundItem.group = pathButtonPool.GetComponent<ToggleGroup>();
            createSoundItemList.Add(soundPlayObj);
            soundPlayObj.GetComponent<TKSoundItem>().GetAudioClip();
                deleteButtonItem.onClick.AddListener(delegate () { this.OnClickDeleteButton(soundPlayObj); });
        }
    }
   
	private void OnToggle_playOrPasueSoundItemClick(Toggle clickToggle,bool value,Button clickButtonItem,GameObject clickgameobj)
    {
        //int currentButtonStata = clickToggle.GetComponent<TKItemState>().playSoundState;
         //Debug.LogError("soundID"+partID+"  ");
         if (value)
         {
            foreach (var item in createSoundItemList)
            {
                item.transform.GetChild(1).GetComponent<Toggle>().transform.GetChild(0).GetComponent<Image>().sprite = PlaySoundSprite[1];
                //item.transform.GetChild(1).GetComponent<Toggle>().isOn = false;
            }
            clickButtonItem.GetComponent<Image>().sprite = PlaySoundSprite[0];
            playAudioSoundList(clickgameobj);
         }
         else
         {    
			foreach (var item in createSoundItemList)
            {
                item.transform.GetChild(1).GetComponent<Toggle>().transform.GetChild(0).GetComponent<Image>().sprite = PlaySoundSprite[1];
                //item.transform.GetChild(1).GetComponent<Toggle>().isOn = false;
            }	 
            clickButtonItem.GetComponent<Image>().sprite = PlaySoundSprite[1];
            //clickButtonItem.transform.parent.GetComponent<Toggle>().isOn=true;
            PauseAudioSoundList(clickgameobj);
         }
       
    }
	private void OnClickDeleteButton(GameObject deleteObj)
    {
        //Debug.LogError("777"+currentID);
		Destroy(deleteObj);
        createSoundItemList.Remove(deleteObj);
        //if (AudioClipDic.ContainsKey(deleteObj))
        //{
        //    AudioClipDic.Remove(deleteObj);

        //}

    }
}
	

  

 

posted @ 2019-11-12 16:51  WalkingSnail  阅读(945)  评论(0)    收藏  举报