Guest User

Untitled

a guest
Aug 11th, 2024
1,035
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5.  
  6. public class RecordAudio : MonoBehaviour
  7. {
  8. private AudioClip recordedClip;
  9. [SerializeField] AudioSource audioSource;
  10. private string filePath = "recording.wav";
  11. private string directoryPath = "Recordings";
  12. private float startTime;
  13. private float recordingLength;
  14.  
  15. private void Awake()
  16. {
  17. if (!Directory.Exists(directoryPath))
  18. {
  19. Directory.CreateDirectory(directoryPath);
  20. }
  21. }
  22.  
  23. public void StartRecording()
  24. {
  25. string device = Microphone.devices[0];
  26. int sampleRate = 44100;
  27. int lengthSec = 3599;
  28.  
  29. recordedClip = Microphone.Start(device, false, lengthSec, sampleRate);
  30. startTime = Time.realtimeSinceStartup;
  31. }
  32.  
  33. public void StopRecording()
  34. {
  35. Microphone.End(null);
  36. recordingLength = Time.realtimeSinceStartup - startTime;
  37. recordedClip = TrimClip(recordedClip, recordingLength);
  38. SaveRecording();
  39. }
  40.  
  41. public void SaveRecording()
  42. {
  43. if (recordedClip != null)
  44. {
  45. filePath = Path.Combine(directoryPath, filePath);
  46. WavUtility.Save(filePath, recordedClip);
  47. Debug.Log("Recording saved as " + filePath);
  48. }
  49. else
  50. {
  51. Debug.LogError("No recording found to save.");
  52. }
  53. }
  54.  
  55. private AudioClip TrimClip(AudioClip clip, float length)
  56. {
  57. int samples = (int)(clip.frequency * length);
  58. float[] data = new float[samples];
  59. clip.GetData(data, 0);
  60.  
  61. AudioClip trimmedClip = AudioClip.Create(clip.name, samples,
  62. clip.channels, clip.frequency, false);
  63. trimmedClip.SetData(data, 0);
  64.  
  65. return trimmedClip;
  66. }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment