using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class Recording : MonoBehaviour {

    private int Frequency = 16000; //录音频率
    private int MicSecond = 300;  //保存300秒内的音频(超出则重新开始录制)
    public Button bStart;
    public Button bStop;
    public Button bPlay;
    public Text tTip;
    public AudioSource au;
    private string device;

    private string recordPath="";
    void Awake() {
        if (File.Exists("Config/recordPath"))
        {
            StreamReader file = new StreamReader("Config/recordPath", Encoding.UTF8);
            recordPath = file.ReadLine().Trim();
            file.Close();
        }
    }
    void Start()
    {
        device = Microphone.devices[0];
        bStart.onClick.AddListener(OnStartClick);
        bStop.onClick.AddListener(OnStopClick);
        bPlay.onClick.AddListener(OnPlayClick);
    }
    int recordLength = 0;
    DateTime sTime;
    void OnStartClick()
    {
        tTip.text += "\n开始录音....";
        au.Stop();
        au.loop = false;
        au.mute = true;
        au.clip = Microphone.Start(device, true, MicSecond, Frequency);
        sTime = DateTime.Now;
    }

    void OnStopClick()
    {
        tTip.text += "\n停止录音!";

        if (!Microphone.IsRecording(device))
            return;
        Microphone.End(device);
        au.Stop();
        TimeSpan sub = new TimeSpan(DateTime.Now.Ticks-sTime.Ticks);
        recordLength = sub.Seconds * Frequency;
        WavFromClip("test.wav", au.clip); //将录音保存为wav
    }
    void OnStopClick(string relativePath)
    {
        tTip.text += "\n停止录音!";

        if (!Microphone.IsRecording(device))
            return;
        Microphone.End(device);
        au.Stop();
        TimeSpan sub = new TimeSpan(DateTime.Now.Ticks-sTime.Ticks);
        recordLength = sub.Seconds * Frequency;
        WavFromClip(recordPath+relativePath+".wav", au.clip); //将录音保存为wav
    }

    void OnPlayClick()
    {
        if (Microphone.IsRecording(device))
            return;
        if (au.clip == null)
            return;
        au.mute = false;
        au.loop = false;
        au.Play();
        tTip.text += "\n播放录音....";
    }

    public void WavFromClip(string WavPosition, AudioClip clip)
    {
        if (Microphone.IsRecording(null))
            return;
        Microphone.End(null);

        using (FileStream fs = CreateEmpty(WavPosition))
        {
            ConvertAndWrite(fs, au.clip);
            WriteHeader(fs, au.clip); //wav文件头
        }
    }

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

        for (int i = 0; i < 44; i++) //为wav文件头留出空间
        {
            fileStream.WriteByte(emptyByte);
        }

        return fileStream;
    }

    private void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    {
        //Debug.Log("————————"+recordLength);
        float[] samples = new float[recordLength];
        //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);
        }
        fileStream.Write(bytesData, 0, bytesData.Length);
    }

 
    private void WriteHeader(FileStream stream, AudioClip clip)
    {
        int hz = clip.frequency;
        int channels = clip.channels;
        int 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); // sampleRate * bytesPerSample*number of channels, here 44100*2*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);

    }
}

  保存其他格式需要插入相关的动态链接库

posted on 2021-10-23 10:05  陌洛  阅读(18)  评论(0编辑  收藏  举报