Click here to Skip to main content
15,747,637 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am working with some audio/video production for my program in C#. Suppose I have an audio file and I want to remove multiple segments of audio from the input file and produce a new output wav file, how would I go about doing that? I have been using a package called NAudio to attempt to pull it off but I have been unsuccessful.

Using this code sample, this is what I tried to do in my program.

What I have tried:

int[] array = {0,3,8,9};
String input = "input.wav"; // 30 seconds
String output = "output.wav";
int i = 0;
while(i < 4){
TrimWavFile(input, output, TimeSpan.FromSeconds(array[i]), TimeSpan.FromSeconds(array[++i]));

This clearly doesn’t work because I’m sure every time it reopens the input file, it uses the new start and stop time to produce the output file. Because of this my output file has only been 29 seconds instead of the expected 26 seconds after removing the 4 seconds from the audio. Does anyone happen to know a method for implementing what I want to do or something even other than NAudio? I am not trying to use FFMPEG or SOX because that would require the use of a Process which I want to avoid. If anyone does happen to know I would appreciate it. Thank you.
Updated 6-Jul-21 5:25am

1 solution

The quick and dirty solution would be to iterate the array in reverse, writing each intermediate step to a temporary file:
string tempPath = GetTempPath();
string tempInputFile = Path.Combine(tempPath, Guid.NewGuid().ToString("N") + ".wav");
string tempOutputFile = Path.Combine(tempPath, Guid.NewGuid().ToString("N") + ".wav");

// Copy the input file to the temp input file:
File.Copy(input, tempInputFile);

for (int i = array.Length - 2; i >= 0; i -= 2)
    // Remove the segment from the temp input file,
    // storing the result in the temp output file:
    TrimWavFile(tempInputFile, tempOutputFile, TimeSpan.FromSeconds(array[i]), TimeSpan.FromSeconds(array[i + 1]);
    // Move the temp output file to the temp input file for the next iteration:
    File.Move(tempOutputFile, tempInputFile);

// Move the temp input file to the final output file:
File.Move(tempInputFile, output);

A better solution would be to change your TrimWavFile function so that it could remove more than one segment without having to load and save the file each time.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900