您现在的位置是:首页 >技术交流 >unity c# 录音并保存为 mp3 或 wav 文件网站首页技术交流

unity c# 录音并保存为 mp3 或 wav 文件

鱼儿-1226 2024-06-17 10:13:44
简介unity c# 录音并保存为 mp3 或 wav 文件

 private int Frequency = 16000; //录音频率
    private int BitRate = 16; //比特率
    private int MicSecond = 2;  //每隔2秒,保存一下录音数据
    public Button bStart;
    public Button bStop;
    public Button bPlay;    
    public Text tTip;
    public AudioSource au;

    void Start () {
        bStart.onClick.AddListener(OnStartClick);
        bStop.onClick.AddListener(OnStopClick);
        bPlay.onClick.AddListener(OnPlayClick);
    }

    void OnStartClick()
    {
        tTip.text += " 开始录音....";
        au.Stop();
        au.loop = false;
        au.mute = true;
        au.clip = Microphone.Start(null, true, MicSecond, Frequency);
    }

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

        if (!Microphone.IsRecording(null))
            return;
        Microphone.End(null);
        au.Stop();
        Mp3FromClip("d:/test.mp3", au.clip); //将录音保存为mp3
        //WavFromClip("d:/test.wav", au.clip); //将录音保存为wav
    }

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

   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)
    {

        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);
    }

    public void Mp3FromClip(string Mp3location, AudioClip clip)
    {
        var samples = new float[clip.samples * clip.channels];
        clip.GetData(samples, 0);

        Int16[] intData = new Int16[samples.Length];
        //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]

        Byte[] bytesData = new Byte[samples.Length * 2];
        //bytesData array is twice the size of
        //dataSource array because a float converted in Int16 is 2 bytes.

        float 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);
        }

        var ms = new MemoryStream(bytesData);

        using (var writer = new LameMP3FileWriter(Mp3location, new WaveFormat(Frequency, BitRate, 1), LAMEPreset.ABR_16))
            ms.CopyTo(writer);       
    }


    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);

    }

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。