Search Unity

Question Please tell me how to save wav, mp3 files using a microphone

Discussion in 'Audio & Video' started by BONGKIKIM, Dec 23, 2021.

  1. BONGKIKIM

    BONGKIKIM

    Joined:
    Jul 16, 2021
    Posts:
    1
    마이크로 입력한 음성 데이터를 저장하고 싶습니다.
    버튼을 누르면 녹음, 재생, 저장을 할 수 있습니다.
    하지만, 녹음과 재생은 가능하지만 저장을 하려면 오류가 생겨 저장하지 못했습니다.
    어디가 잘못된걸까요?

    I want to save the voice data input by the microphone.
    Press the button to record, play, and save.
    However, recording and playback are possible, but when trying to save, an error occurred and it could not be saved.
    Where is it wrong?
    & Do you know BTS?

    //UI Touch Script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System;
    4. using UnityEngine;
    5. using UnityEngine.Audio;
    6.  
    7. public class MIc : MonoBehaviour
    8. {
    9.     AudioSource _audioSource;
    10.    
    11.     public bool _useMicrophone;
    12.     public string _selectedDevice;
    13.  
    14.     public AudioMixerGroup _mixerGroupMicrophone, _mixerGroupMaster;
    15.  
    16.  
    17.     private void Start()
    18.     {
    19.         _audioSource = GetComponent<AudioSource>();
    20.         _mixerGroupMaster = GetComponent<AudioMixerGroup>();
    21.  
    22.     }
    23.  
    24.     public void PlayVoice()
    25.     {
    26.         _audioSource.Play();
    27.         Debug.Log("재생중");
    28.     }
    29.     public void RecVoice()
    30.     {
    31.         _useMicrophone = true;
    32.         if (_useMicrophone)
    33.         {
    34.             if (Microphone.devices.Length > 0)
    35.             {
    36.                 _selectedDevice = Microphone.devices[0].ToString();
    37.                 _audioSource.outputAudioMixerGroup = _mixerGroupMicrophone;
    38.                 _audioSource.clip = Microphone.Start(_selectedDevice, true, 10, AudioSettings.outputSampleRate);
    39.                 Debug.Log("녹음중");
    40.             }
    41.         }
    42.         else
    43.         {
    44.             _useMicrophone = false;
    45.         }
    46.     }
    47.  
    48.     public void SaveVoice()
    49.     {
    50.         SavWav.Save("Voice1", _audioSource.clip);
    51.         Debug.Log("저장중");
    52.     }
    53. }
    54.  
    Code (CSharp):
    1. using System;
    2. using System.IO;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public static class SavWav
    7. {
    8.     const int HEADER_SIZE = 44;
    9.    
    10.     public static bool Save(string filename, AudioClip clip)
    11.     {
    12.         if (!filename.ToLower().EndsWith(".MP3"))
    13.         {
    14.             filename += ".MP3";
    15.         }
    16.  
    17.        var filepath = Path.Combine(Application.persistentDataPath, filename);
    18.         Debug.Log(filepath);
    19.        
    20.  
    21.         Directory.CreateDirectory(Path.GetDirectoryName(filepath));
    22.  
    23.         using (var fileStream = CreateEmpty(filepath))
    24.         {
    25.             ConvertAndWrite(fileStream, clip);
    26.  
    27.             WriteHeader(fileStream, clip);
    28.         }
    29.         return true;
    30.  
    31.     }
    32.     public static AudioClip TrimSilence(AudioClip clip, float min)
    33.     {
    34.         var samples = new float[clip.samples];
    35.  
    36.         clip.GetData(samples, 0);
    37.  
    38.         return TrimSilence(new List<float>(samples), min, clip.channels, clip.frequency);
    39.     }
    40.     public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz)
    41.     {
    42.         return TrimSilence(samples, min, channels, hz, false, false);
    43.     }
    44.  
    45.     public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream)
    46.     {
    47.         int i;
    48.  
    49.         for (i = 0; i < samples.Count; i++)
    50.         {
    51.             if (Mathf.Abs(samples[i]) > min)
    52.             {
    53.                 break;
    54.             }
    55.  
    56.         }
    57.         samples.RemoveRange(0, i);
    58.         for (i = samples.Count - 1; i > 0; i--)
    59.         {
    60.             if (Mathf.Abs(samples[i]) > min)
    61.             {
    62.                 break;
    63.             }
    64.         }
    65.         samples.RemoveRange(i, samples.Count - i);
    66.  
    67.         var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
    68.         clip.SetData(samples.ToArray(), 0);
    69.  
    70.         return clip;
    71.     }
    72.  
    73.     static FileStream CreateEmpty(string filepath)
    74.     {
    75.         var fileStream = new FileStream(filepath, FileMode.Create);
    76.         byte emptyByte = new byte();
    77.  
    78.         for (int i = 0; i < HEADER_SIZE; i++)
    79.         {
    80.             fileStream.WriteByte(emptyByte);
    81.         }
    82.         return fileStream;
    83.     }
    84.     static void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    85.     {
    86.         var samples = new float[clip.samples];
    87.  
    88.         clip.GetData(samples, 0);
    89.  
    90.         Int16[] intData = new Int16[samples.Length];
    91.  
    92.         Byte[] bytesData = new Byte[samples.Length * 2];
    93.  
    94.         int rescaleFactor = 32767;
    95.  
    96.         for (int i = 0; i < samples.Length; i++)
    97.         {
    98.             intData[i] = (short)(samples[i] * rescaleFactor);
    99.             Byte[] byteArr = new Byte[2];
    100.             byteArr = BitConverter.GetBytes(intData[i]);
    101.             byteArr.CopyTo(bytesData, i * 2);
    102.         }
    103.         fileStream.Write(bytesData, 0, bytesData.Length);
    104.     }
    105.  
    106.  
    107.     static void WriteHeader(FileStream fileStream, AudioClip clip)
    108.     {
    109.         var hz = clip.frequency;
    110.         var channels = clip.channels;
    111.         var samples = clip.samples;
    112.  
    113.         fileStream.Seek(0, SeekOrigin.Begin);
    114.  
    115.         Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
    116.         fileStream.Write(riff, 0, 4);
    117.  
    118.         Byte[] chunkSize = BitConverter.GetBytes(fileStream.Length - 8);
    119.         fileStream.Write(chunkSize, 0, 4);
    120.  
    121.         Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
    122.         fileStream.Write(wave, 0, 4);
    123.  
    124.         Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt");
    125.         fileStream.Write(fmt, 0, 4);
    126.  
    127.         Byte[] subChunk1 = BitConverter.GetBytes(16);
    128.         fileStream.Write(subChunk1, 0, 4);
    129.  
    130.         UInt16 two = 2;
    131.         UInt16 one = 1;
    132.  
    133.         Byte[] audioFormat = BitConverter.GetBytes(one);
    134.         fileStream.Write(audioFormat, 0, 2);
    135.  
    136.         Byte[] numChannels = BitConverter.GetBytes(channels);
    137.         fileStream.Write(numChannels, 0, 2);
    138.  
    139.         Byte[] sampleRate = BitConverter.GetBytes(hz);
    140.         fileStream.Write(sampleRate, 0, 4);
    141.  
    142.         Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
    143.         fileStream.Write(byteRate, 0, 4);
    144.  
    145.         UInt16 blockAlign = (ushort)(channels * 2);
    146.         fileStream.Write(BitConverter.GetBytes(blockAlign), 0, 2);
    147.  
    148.         UInt16 bps = 16;
    149.         Byte[] bitsPerSample = BitConverter.GetBytes(bps);
    150.         fileStream.Write(bitsPerSample, 0, 2);
    151.  
    152.         Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
    153.         fileStream.Write(datastring, 0, 4);
    154.  
    155.         Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
    156.         fileStream.Write(subChunk2, 0, 4);
    157.     }
    158. }
    159.  
     

    Attached Files:

  2. The_Island

    The_Island

    Unity Technologies

    Joined:
    Jun 1, 2021
    Posts:
    502
    Can you be a little more specific by "an error occurred and it could not be saved". Can you share the error? Was the file created? If you open it, how does it looks?