- Home /
How to detect volume change and trim the beginning of AudioClip?
Hello! I made a drumpad app, which records audio from the device microphone and then plays the recorded audio. I'm using SavWav to trim the end of the clip, but I don't know how to trim the beginning of the clip. I want to cut the silence at the beginning where the volume is close to 0 and create a new clip that begins at the point when the volume gets higher. Any idea on how to do that? Here's the part of SavWav which deals with the trimming.
public static AudioClip TrimSilence(AudioClip clip, float min) {
var samples = new float[clip.samples];
clip.GetData(samples, 0);
return TrimSilence(new List<float>(samples), min, clip.channels, clip.frequency);
}
public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz) {
return TrimSilence(samples, min, channels, hz, false, false);
}
public static AudioClip TrimSilence(List<float> samples, float min, int channels, int hz, bool _3D, bool stream) {
int i;
for (i=0; i<samples.Count; i++) {
if (Mathf.Abs(samples[i]) > min) {
break;
}
}
samples.RemoveRange(0, i);
for (i=samples.Count - 1; i>0; i--) {
if (Mathf.Abs(samples[i]) > min) {
break;
}
}
samples.RemoveRange(i, samples.Count - i);
var clip = AudioClip.Create("TempClip", samples.Count, channels, hz, _3D, stream);
clip.SetData(samples.ToArray(), 0);
return clip;
}
Answer by Lukas-Wendt · Apr 18, 2018 at 03:53 PM
The TrimSilence method in SavWav already trims both beginning and end (see line 15-20), what is not working for you?
Also, this way om trimming does not trim at a zero-crossing, which means that you will most likely hear clicks at the beginning and end of your trimmed clips.
Answer by snifo · Apr 18, 2018 at 05:00 PM
I thought that it cuts both beginning and end but I was not sure. The thing is that there is some static noise at the beginning, which is inevitable when you're using the mic, but TrimSilence does not cut it, it recognizes it as important. Now that I know it cuts both ends I think the problem can be solved with a noise reduction plugin or something relevant. Thank you!
I would think that adjusting the $$anonymous$$ parameter of TrimSilence can help you get rid of the noise. It should just be a question of finding a good value.