void StartRecording()
{
playBackAudioSource.clip = Microphone.Start(currentMicrophoneName, false, 20, microphoneMaximumFrequqency);
}
void StopRecording()
{
int lastPosition= Microphone.GetPosition(currentMicrophoneName);
Microphone.End(currentMicrophoneName);
float[] originalSamples = new float[playBackAudioSource.clip.samples];
playBackAudioSource.clip.GetData(originalSamples, 0);
float[] samplesToRetain = new float[lastPosition];
Array.Copy(originalSamples, samplesToRetain, samplesToRetain.Length - 1);
AudioClip trimmedClip = AudioClip.Create("playRecordClip", samplesToRetain.Length, playBackAudioSource.clip.channels, playBackAudioSource.clip.frequency, false);
for (int i = 0; i < samplesToRetain.Length; i++)
{
Debug.Log(samplesToRetain[i]);
}
trimmedClip.SetData(samplesToRetain, 0);
playBackAudioSource.clip = trimmedClip;
Debug.Log("Trimmed audio clip created!");
}
void Update()
{
Debug.Log(Microphone.IsRecording(currentMicrophoneName));
if (record == true)
{
if (!Microphone.IsRecording(currentMicrophoneName))
{
StartRecording();
}
}
else
{
if (Microphone.IsRecording(currentMicrophoneName))
{
StopRecording();
playBackAudioSource.Play();
}
}
}
Hi
I wrote this code so that I can get input from users via microphone. The problem is that you always have to specify a fixed length when starting the recording, which is not always fixed for me and is known at the beginning (and it will be always different). To get around this, I thought that I could trim the audio clips afterwards. I tried it out in different ways. Here you can see my last attempt ( previously I measured the time and calculated the number of samples that need to be preserved and here I used the GetPosition). The problem now is that the created audio clips have the right length but no audio. More precisely, it is played correctly for the first time (because of Play call at the bottom of Update). Then when I go to the audio clip in the inspector and play it manually, I hear nothing. This confuses me completely. I have tested the code several times and scrutinized it. Arrays (originalSamples and samplesToRetain) are not empty and also have valid values (all between -1 and 1).
I have tried it with different Unity versions (2021.3.15f1 and 2022.3.40f). I would appreciate your advice. If you have a better idea for trimming, I would also be grateful. I got this idea from old posts in this and other forums.
Thanks in advance.