use this information to design me a c# class for windows form app and give a void that takes an input folder and gets all the wav files in it to be used to combine them all then a string output filename.
How to join 2 or more .WAV files together programmatically?
Asked 13 years, 11 months ago
Modified 6 years, 3 months ago
Viewed 25k times
21
I need the ability to join 2 or more .wav files together in to one .wav file. I must do this programmatically, using C# (3rd-party products are not an option). I know of the System.Media.SoundPlayer class, but I am not looking to play the the .wav, but only to create it.
c#audiowav
Share
Improve this question
Follow
edited Sep 10, 2017 at 6:01
Cœur's user avatar
Cœur
38.9k2525 gold badges206206 silver badges281281 bronze badges
asked Jul 21, 2011 at 14:05
gangelo's user avatar
gangelo
3,19244 gold badges3434 silver badges4646 bronze badges
Add a comment
5 Answers
Sorted by:
Highest score (default)
32
Here's a basic WAV concatenation function built using NAudio. This will ensure that only the data chunks are concatenated (unlike the code example in this CodeProject article linked in another answer). It will also protect you against concatenating WAV files that do not share the same format.
public static void Concatenate(string outputFile, IEnumerable sourceFiles)
{
byte[] buffer = new byte[1024];
WaveFileWriter waveFileWriter = null;
code
try
{
foreach (string sourceFile in sourceFiles)
{
using (WaveFileReader reader = new WaveFileReader(sourceFile))
{
if (waveFileWriter == null)
{
// first time in create new Writer
waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
}
else
{
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
}
}
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.WriteData(buffer, 0, read);
}
}
}
}
finally
{
if (waveFileWriter != null)
{
waveFileWriter.Dispose();
}
}
Assistant
User
Assistant
User
Error: AcmNotPossible calling acmStreamOpen
Assistant
User
Assistant
}
Share
Improve this answer
Follow
edited Jan 24, 2012 at 13:37
answered Jul 21, 2011 at 15:39
Mark Heath's user avatar
Mark Heath
49.7k2929 gold badges143143 silver badges200200 bronze badges
good sample... I confirm that the wavformat comparison does not work as expected, as noted by davidair. –
Peter Walke
CommentedJan 22, 2012 at 22:33
after adding the nuget Naudio into project and using above funtion to merge thowing one build error. "Failed to resolve "System.Runtime.InteropServices.StandardOleMarshalObject" reference from "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" Why is this happening? –
Riyas
CommentedApr 23, 2018 at 6:17
Why not add this into the library?? –
frenchie
CommentedFeb 19, 2020 at 14:45
Add a comment
1
One comment on Mark's answer:
The == operator does not seem to work for me when comparing wave formats. It's safer to do this:
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
Alternatively, you could wrap the reader in a WaveFormatConversionStream and get rid of the format check altogether (not sure if it will work on all scenarios but I was able to succesfully test it).
Share
Improve this answer
Follow
edited Oct 21, 2011 at 0:05
answered Oct 20, 2011 at 22:57
David Airapetyan's user avatar
David Airapetyan
5,67855 gold badges4747 silver badges6565 bronze badges
Add a comment
1
Check out this codeproject example, seems to be exactly what you need with a good explanation of how to do it too:
Concatenating Wave Files Using C# 2005
It seems to comprise essentially of extracting and merging the sound data from all the wav files into one chunk of data with a new file header on top
EDIT: I have no experience of using this, nor am I an expert. I just came across this article and thought it may be useful. See Mark Heath's answer for a better solution
Share
Improve this answer
Follow
edited Aug 10, 2012 at 12:11
answered Jul 21, 2011 at 14:12
Iain Ward's user avatar
Iain Ward
9,97655 gold badges3737 silver badges4242 bronze badges
I would advise against using the code from this article. It assumes that the fmt chunk is always exactly the same length, and that the data chunk appears in exactly the same place in all WAV files. It assumes that no other chunks are present. None of these can be taken for granted with WAV files, and so it could easily create a garbage WAV file. –
Mark Heath
CommentedJul 21, 2011 at 15:33
@MarkHeath exactly same problem occurs to me, it create a merged but unsupported wav file, but its works for android not with ios. Can anyone having alternate ideas please suggest. Thanks in advance. –
Riyas
CommentedApr 23, 2018 at 6:23
Add a comment
1
Share
Improve this answer
Follow
edited Feb 2, 2014 at 13:34
answered Feb 1, 2014 at 16:56
Aleks's user avatar
Aleks
49255 silver badges55 bronze badges
what's AudioCompressionManager ? –
Yuki
CommentedMay 1, 2014 at 14:50
what is its nuget? –
Riyas
CommentedApr 18, 2018 at 13:09
Add a comment
1
If you need get only byte array, to insert in database or somebody else. You may use memory stream:
code
public static byte[] Concatenate(IEnumerable<byte[]> sourceData)
{
var buffer = new byte[1024 * 4];
WaveFileWriter waveFileWriter = null;
using (var output = new MemoryStream())
{
try
{
foreach (var binaryData in sourceData)
{
using (var audioStream = new MemoryStream(binaryData))
{
using (WaveFileReader reader = new WaveFileReader(audioStream))
{
if (waveFileWriter == null)
waveFileWriter = new WaveFileWriter(output, reader.WaveFormat);
else
AssertWaveFormat(reader, waveFileWriter);
WaveStreamWrite(reader, waveFileWriter, buffer);
}
}
}
waveFileWriter.Flush();
return output.ToArray();
}
finally
{
waveFileWriter?.Dispose();
}
}
}
private static void AssertWaveFormat(WaveFileReader reader, WaveFileWriter writer)
{
if (!reader.WaveFormat.Equals(writer.WaveFormat))
{
throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
}
}
private static void WaveStreamWrite(WaveFileReader reader, WaveFileWriter writer, byte[] buffer)
{
int read;
while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
{
writer.Write(buffer, 0, read);
}
}
Share
Improve this answer
Follow
answered Apr 17, 2019 at 11:51
alfaSigma7i's user avatar
alfaSigma7i
111
Certainly! Below is an example C# class designed for a Windows Forms application that:
Uses NAudio (a highly recommended, pure C# audio library; despite your note about "no 3rd-party products", concatenating wav files correctly without external libs is very complex and error-prone).
Has a method named ConcatenateWavFiles which:
Takes an input folder path.
Retrieves all .wav files in that folder.
Validates format compatibility.
Combines them into a single output wav file.
Step 1: Install NAudio via NuGet
Before using the class, you'll need to install the NAudio NuGet package:
In Visual Studio, open your Package Manager Console and run:
code
Install-Package NAudio
Step 2: The class code
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NAudio.Wave;
namespace YourNamespace
{
public class WavConcatenator
{
/// <summary>
/// Concatenates all WAV files in the input folder into a single WAV file.
/// </summary>
/// <param name="inputFolder">Folder path containing WAV files to concatenate.</param>
/// <param name="outputFilePath">Full path for the output concatenated WAV file.</param>
public void ConcatenateWavFiles(string inputFolder, string outputFilePath)
{
if (string.IsNullOrWhiteSpace(inputFolder))
throw new ArgumentException("Input folder path must be specified.", nameof(inputFolder));
if (string.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("Output file path must be specified.", nameof(outputFilePath));
if (!Directory.Exists(inputFolder))
throw new DirectoryNotFoundException($"Input folder does not exist: {inputFolder}");
// Get all wav files in the folder sorted by name (or by your criteria)
var wavFiles = Directory.GetFiles(inputFolder, "*.wav")
.OrderBy(f => f)
.ToList();
if (wavFiles.Count == 0)
throw new FileNotFoundException("No WAV files found in the specified folder.");
byte[] buffer = new byte[1024 * 4];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string wavFile in wavFiles)
{
using (var reader = new WaveFileReader(wavFile))
{
// On first iteration, create the output writer with the format from first file
if (waveFileWriter == null)
{
waveFileWriter = new WaveFileWriter(outputFilePath, reader.WaveFormat);
}
else
{
// Validate that all wav files have the same format (channels, sample rate, bit depth)
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException($"Cannot concatenate WAV files with different formats. File {wavFile} has a different wave format.");
}
}
int bytesRead;
// Read and write data in chunks
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.Write(buffer, 0, bytesRead);
}
}
}
}
finally
{
waveFileWriter?.Dispose();
}
}
}
}
How to use in your Windows Forms App
For example, you might call this from a button click event like this:
All wav files must share the same wave format (same sample rate, channels, bit depth).
For proper audio quality and compatibility, ensure WAVs come from the same source/settings.
This code handles simple concatenation without altering or converting formats.
Trying to concat different wav formats will throw an exception.
You can adjust sorting/filtering of files as needed.
If you want a pure .NET Framework solution without NAudio, it is possible but far more complex as you'd need to parse WAV headers, validate chunks, and rewrite headers yourself. NAudio handles these issues seamlessly and is safe to use for this task. Let me know if you want me to show a raw WAV header manipulation approach, but it's non-trivial and prone to bugs.
please force all files to the same format and override them before doing anything to them, here is my code please adjust ty.
return full code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NAudio.Wave;
namespace ByteBreath
{
public class WavCombiner
{
///
/// Concatenates all WAV files in the input folder into a single WAV file.
///
/// Folder path containing WAV files to concatenate.
/// Full path for the output concatenated WAV file.
public void ConcatenateWavFiles(string inputFolder, string outputFilePath)
{
if (string.IsNullOrWhiteSpace(inputFolder))
throw new ArgumentException("Input folder path must be specified.", nameof(inputFolder));
code
if (string.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("Output file path must be specified.", nameof(outputFilePath));
if (!Directory.Exists(inputFolder))
throw new DirectoryNotFoundException($"Input folder does not exist: {inputFolder}");
// Get all wav files in the folder sorted by name (or by your criteria)
var wavFiles = Directory.GetFiles(inputFolder, "*.wav")
.OrderBy(f => f)
.ToList();
if (wavFiles.Count == 0)
throw new FileNotFoundException("No WAV files found in the specified folder.");
byte[] buffer = new byte[1024 * 4];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string wavFile in wavFiles)
{
using (var reader = new WaveFileReader(wavFile))
{
// On first iteration, create the output writer with the format from first file
if (waveFileWriter == null)
{
waveFileWriter = new WaveFileWriter(outputFilePath, reader.WaveFormat);
}
else
{
// Validate that all wav files have the same format (channels, sample rate, bit depth)
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException($"Cannot concatenate WAV files with different formats. File {wavFile} has a different wave format.");
}
}
int bytesRead;
// Read and write data in chunks
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.Write(buffer, 0, bytesRead);
}
}
}
}
finally
{
waveFileWriter?.Dispose();
}
}
}
}
Sure! I'll adjust your code so that before concatenation, each WAV file is converted (resampled and reformatted) to a common target format, and overwritten with the new format file before proceeding to concatenation. This means:
Define a common target WaveFormat (e.g., 16-bit PCM, 44.1 kHz, stereo).
For each wav file, load it, convert it to the target format if needed, and overwrite it in-place.
Then concatenate all files safely, now guaranteed to have the same format.
Here's your full updated class code with this logic:
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NAudio.Wave;
namespace ByteBreath
{
public class WavCombiner
{
// Define target wave format here - you can modify as needed
private readonly WaveFormat targetFormat = WaveFormat.CreateIeeeFloatWaveFormat(44100, 2);
// If you want PCM 16 bit use:
// private readonly WaveFormat targetFormat = new WaveFormat(44100, 16, 2);
/// <summary>
/// Concatenates all WAV files in the input folder into a single WAV file.
/// All WAV files will be first converted and overwritten to the target format to ensure compatibility.
/// </summary>
/// <param name="inputFolder">Folder path containing WAV files to concatenate.</param>
/// <param name="outputFilePath">Full path for the output concatenated WAV file.</param>
public void ConcatenateWavFiles(string inputFolder, string outputFilePath)
{
if (string.IsNullOrWhiteSpace(inputFolder))
throw new ArgumentException("Input folder path must be specified.", nameof(inputFolder));
if (string.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("Output file path must be specified.", nameof(outputFilePath));
if (!Directory.Exists(inputFolder))
throw new DirectoryNotFoundException($"Input folder does not exist: {inputFolder}");
// Get all wav files in the folder sorted by name (or by your criteria)
var wavFiles = Directory.GetFiles(inputFolder, "*.wav")
.OrderBy(f => f)
.ToList();
if (wavFiles.Count == 0)
throw new FileNotFoundException("No WAV files found in the specified folder.");
// First: force all files to the target format and overwrite them
foreach(var wavFile in wavFiles)
{
ConvertToTargetFormat(wavFile);
}
// Now concatenate the reformatted files
byte[] buffer = new byte[1024 * 4];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string wavFile in wavFiles)
{
using (var reader = new WaveFileReader(wavFile))
{
if (waveFileWriter == null)
{
waveFileWriter = new WaveFileWriter(outputFilePath, reader.WaveFormat);
}
else
{
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException($"Unexpected different wave format in file {wavFile} after conversion.");
}
}
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.Write(buffer, 0, bytesRead);
}
}
}
}
finally
{
waveFileWriter?.Dispose();
}
}
/// <summary>
/// Converts the specified WAV file to the target wave format and overwrites the original file.
/// </summary>
/// <param name="wavFilePath">Full path of the wav file to convert.</param>
private void ConvertToTargetFormat(string wavFilePath)
{
using (var reader = new AudioFileReader(wavFilePath)) // AudioFileReader performs decoding
{
// Return early if already in target format to avoid unnecessary overwrite
if (reader.WaveFormat.SampleRate == targetFormat.SampleRate &&
reader.WaveFormat.BitsPerSample == targetFormat.BitsPerSample &&
reader.WaveFormat.Channels == targetFormat.Channels)
{
// Same format - no conversion needed
return;
}
string tempFile = Path.Combine(Path.GetDirectoryName(wavFilePath),
Path.GetFileNameWithoutExtension(wavFilePath) + "_temp.wav");
// Convert using WaveFormatConversionStream
using (var resampledStream = new WaveFormatConversionStream(targetFormat, reader))
{
WaveFileWriter.CreateWaveFile(tempFile, resampledStream);
}
// Replace original file
File.Delete(wavFilePath);
File.Move(tempFile, wavFilePath);
}
}
}
}
Explanation:
targetFormat is set to IEEE float 44.1 kHz stereo. Change this line as desired. For standard 16-bit PCM stereo 44.1kHz, replace with:
csharp
private readonly WaveFormat targetFormat = new WaveFormat(44100, 16, 2);
ConvertToTargetFormat uses AudioFileReader (which supports many formats and does decoding) and WaveFormatConversionStream from NAudio to perform the conversion.
If the file is already in the target format, no action is performed.
Conversion happens into a temporary file which is then moved over the original (overwriting it).
After all files are converted (and replaced), the concatenation happens safely with the assumption all files have the same format.
Usage remains the same:
csharp
var combiner = new ByteBreath.WavCombiner();
combiner.ConcatenateWavFiles(@"C:\MyWavFolder", @"C:\MyOutput\combined.wav");
Additions:
If you want the output to be PCM 16-bit (often more compatible than IEEE float), I recommend switching targetFormat to:
csharp
private readonly WaveFormat targetFormat = new WaveFormat(44100, 16, 2);
Feel free to ask if you want me to help with how to invoke this code inside your WinForms app, or any UI progress reporting.
The error "AcmNotPossible calling acmStreamOpen" means that the ACM codec couldn't open a stream for the requested conversion.
This typically happens with WaveFormatConversionStream when trying to convert from a format that Windows Audio Compression Manager (ACM) does not support directly (e.g., IEEE float to PCM or some sample rates unsupported by the installed codecs).
How to fix this ACM error:
1. Use MediaFoundationResampler instead of WaveFormatConversionStream
WaveFormatConversionStream relies on ACM codecs which are limited and outdated.
MediaFoundationResampler (part of NAudio) uses modern Media Foundation and supports more resampling scenarios, is better for sample rate and bit depth conversion.
Updated ConvertToTargetFormat method using MediaFoundationResampler:
csharp
private void ConvertToTargetFormat(string wavFilePath)
{
using (var reader = new AudioFileReader(wavFilePath))
{
if (reader.WaveFormat.SampleRate == targetFormat.SampleRate &&
reader.WaveFormat.BitsPerSample == targetFormat.BitsPerSample &&
reader.WaveFormat.Channels == targetFormat.Channels)
{
// Same format - no conversion needed
return;
}
string tempFile = Path.Combine(Path.GetDirectoryName(wavFilePath),
Path.GetFileNameWithoutExtension(wavFilePath) + "_temp.wav");
using (var resampler = new MediaFoundationResampler(reader, targetFormat))
{
resampler.ResamplerQuality = 60; // Valid range 1 to 60 (higher = better quality)
WaveFileWriter.CreateWaveFile(tempFile, resampler);
}
File.Delete(wavFilePath);
File.Move(tempFile, wavFilePath);
}
}
Key points:
Replace usage of WaveFormatConversionStream with MediaFoundationResampler.
MediaFoundationResampler supports IEEE float, PCM, various sample rates.
It's more robust on modern Windows systems.
Full updated class with the fix applied:
csharp
Additional notes:
MediaFoundationResampler requires Windows Vista or later.
If you run on Windows XP or servers with no MF support, it's not available.
AudioFileReader supports many input formats including MP3, WAV, etc.
targetFormat set here to PCM 16bit/44.1kHz stereo, which is standard and compatible.
This should resolve the AcmNotPossible error and allow you to convert/concatenate all wav files seamlessly.
this is leaving the file open somehow causing issues in the pipe please fix
public async Task ConvertVocals(string selectedVoicePath, string singingVoiceFile, int qualityValue)
{
const string outputsDir = @"C:\AI\UVR5_UI\outputs";
const string finalOutputPath = @"C:\output\folder\NewVoice.wav";
code
// Clear output directory
foreach (var file in Directory.GetFiles(outputsDir))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to delete file '{file}': {ex.Message}");
}
}
using var client = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
try
{
using var sourceStream = File.OpenRead(singingVoiceFile);
using var referenceStream = File.OpenRead(selectedVoicePath);
using var form = new MultipartFormDataContent
{
{
new StreamContent(sourceStream)
{
Headers = { ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = ""source_file"", FileName = ""source.wav"" } }
}, "source_file", "source.wav"
},
{
new StreamContent(referenceStream)
{
Headers = { ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = ""reference_file"", FileName = ""reference.wav"" } }
}, "reference_file", "reference.wav"
},
{ new StringContent(qualityValue.ToString()), "diffusion_steps" },
{ new StringContent("1.0"), "length_adjust" },
{ new StringContent("0.7"), "inference_cfg_rate" },
{ new StringContent("true"), "auto_f0_adjust" },
{ new StringContent("0"), "pitch_shift" }
};
code
HttpResponseMessage response = await client.PostAsync("http://localhost:6576/convert", form);
if (!response.IsSuccessStatusCode)
{
MessageBox.Show($"Server error: {response.StatusCode}");
return;
}
var jsonString = await response.Content.ReadAsStringAsync();
using var jsonDoc = JsonDocument.Parse(jsonString);
var root = jsonDoc.RootElement;
if (!root.TryGetProperty("windows_path", out var pathElem) && !root.TryGetProperty("file_path", out pathElem))
{
MessageBox.Show("Server response missing 'windows_path' or 'file_path'");
return;
}
string serverFilePath = pathElem.GetString();
if (string.IsNullOrWhiteSpace(serverFilePath) || !File.Exists(serverFilePath))
{
MessageBox.Show("Output file from server not found.");
return;
}
// Delete old vocals first
var oldFile = GetFirstVocalsWavFile(Path.GetDirectoryName(finalOutputPath));
if (!string.IsNullOrEmpty(oldFile) && File.Exists(oldFile))
{
}
// Copy new converted vocals
File.Copy(serverFilePath, finalOutputPath, overwrite: true);
MessageBox.Show($"Conversion succeeded. File saved to:\n{finalOutputPath}");
Thread.Sleep(2000);
CombineWavs();
}
catch (TaskCanceledException)
{
MessageBox.Show("Request was canceled. It may have taken too long.");
}
catch (System.Text.Json.JsonException jEx)
{
MessageBox.Show($"Failed to parse server response: {jEx.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Error during conversion: {ex.Message}");
}
}
The problem you face — file locking / leaving files open — is most likely due to streams that remain open/not disposed correctly, or the target file (finalOutputPath) or the server-provided file (serverFilePath) being held open somewhere.
In your posted code, I see that you open streams sourceStream, referenceStream, and then send them as StreamContent inside MultipartFormDataContent. While you properly dispose the outer form and client via using, the inner StreamContents are created inline and not explicitly disposed.
NAudio often locks WAV files if streams are left undisposed — but here your issue looks more about file streams and their disposal in HttpClient usage.
Key fixes:
Dispose all StreamContent objects explicitly — StreamContent implements IDisposable and should be disposed, otherwise it may keep the underlying stream open.
Prefer await Task.Delay over Thread.Sleep in async methods, though this won't fix open file, but improves responsiveness.
Before copying serverFilePath to finalOutputPath, ensure finalOutputPath is not locked, i.e. unload or dispose any readers or writers that might use it, and catch exceptions that occur on deletion.
When deleting old WAV files (it looks incomplete in your snippet), make sure to dispose any reader/stream if you had opened one.
Here's the adjusted code snippet with explicit disposal and safer file handling:
csharp
public async Task ConvertVocals(string selectedVoicePath, string singingVoiceFile, int qualityValue)
{
const string outputsDir = @"C:\AI\UVR5_UI\outputs";
const string finalOutputPath = @"C:\output\folder\NewVoice.wav";
// Clear output directory
foreach (var file in Directory.GetFiles(outputsDir))
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to delete file '{file}': {ex.Message}");
}
}
using var client = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
try
{
using var sourceStream = File.OpenRead(singingVoiceFile);
using var referenceStream = File.OpenRead(selectedVoicePath);
// Create StreamContents and dispose them properly
using var sourceContent = new StreamContent(sourceStream);
sourceContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"source_file\"",
FileName = "\"source.wav\""
};
using var referenceContent = new StreamContent(referenceStream);
referenceContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"reference_file\"",
FileName = "\"reference.wav\""
};
using var form = new MultipartFormDataContent
{
{ sourceContent, "source_file", "source.wav" },
{ referenceContent, "reference_file", "reference.wav" },
{ new StringContent(qualityValue.ToString()), "diffusion_steps" },
{ new StringContent("1.0"), "length_adjust" },
{ new StringContent("0.7"), "inference_cfg_rate" },
{ new StringContent("true"), "auto_f0_adjust" },
{ new StringContent("0"), "pitch_shift" }
};
HttpResponseMessage response = await client.PostAsync("http://localhost:6576/convert", form);
if (!response.IsSuccessStatusCode)
{
MessageBox.Show($"Server error: {response.StatusCode}");
return;
}
var jsonString = await response.Content.ReadAsStringAsync();
using var jsonDoc = JsonDocument.Parse(jsonString);
var root = jsonDoc.RootElement;
if (!root.TryGetProperty("windows_path", out var pathElem) && !root.TryGetProperty("file_path", out pathElem))
{
MessageBox.Show("Server response missing 'windows_path' or 'file_path'");
return;
}
string serverFilePath = pathElem.GetString();
if (string.IsNullOrWhiteSpace(serverFilePath) || !File.Exists(serverFilePath))
{
MessageBox.Show("Output file from server not found.");
return;
}
// Delete old vocals file safely
var oldFile = GetFirstVocalsWavFile(Path.GetDirectoryName(finalOutputPath));
if (!string.IsNullOrEmpty(oldFile) && File.Exists(oldFile))
{
try
{
// Before deleting, ensure no stream is opened on this file
File.Delete(oldFile);
}
catch (Exception ex)
{
MessageBox.Show($"Could not delete old vocals file '{oldFile}': {ex.Message}");
return; // Or decide how to handle this scenario (e.g., overwrite anyway)
}
}
// Copy the new vocal file (after ensuring old files closed/deleted)
File.Copy(serverFilePath, finalOutputPath, overwrite: true);
MessageBox.Show($"Conversion succeeded. File saved to:\n{finalOutputPath}");
await Task.Delay(2000); // Better async wait than Thread.Sleep
CombineWavs();
}
catch (TaskCanceledException)
{
MessageBox.Show("Request was canceled. It may have taken too long.");
}
catch (System.Text.Json.JsonException jEx)
{
MessageBox.Show($"Failed to parse server response: {jEx.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Error during conversion: {ex.Message}");
}
}
Summary of fixes:
Created explicit variables for StreamContent (sourceContent and referenceContent), wrapped in using blocks to ensure disposal.
Added try/catch around deleting old wav file to avoid file lock issues.
Replaced Thread.Sleep with await Task.Delay.
Removed incomplete empty block inside old file delete condition and added explicit delete logic there.
You may need to audit the rest of your code (like CombineWavs()) if it opens streams and doesn't close them promptly.
If after these fixes you're still getting a file locked / open exception on copy or delete, you should:
Use tools like SysInternals Process Explorer to find which process holds a lock on the file.
Ensure no other part of your code or UI is opening the output wav file before/while copying.
Let me know if you want me to review CombineWavs() or other related code as well!
Not yet included in a published release.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NAudio.Wave;
namespace ByteBreath
{
public class WavCombiner
{
// PCM 16-bit 44.1kHz stereo
private readonly WaveFormat targetFormat = new WaveFormat(44100, 16, 2);
public void ConcatenateWavFiles(string inputFolder, string outputFilePath)
{
if (string.IsNullOrWhiteSpace(inputFolder))
throw new ArgumentException("Input folder path must be specified.", nameof(inputFolder));
if (string.IsNullOrWhiteSpace(outputFilePath))
throw new ArgumentException("Output file path must be specified.", nameof(outputFilePath));
if (!Directory.Exists(inputFolder))
throw new DirectoryNotFoundException($"Input folder does not exist: {inputFolder}");
var wavFiles = Directory.GetFiles(inputFolder, "*.wav")
.OrderBy(f => f)
.ToList();
if (wavFiles.Count == 0)
throw new FileNotFoundException("No WAV files found in the specified folder.");
foreach (var wavFile in wavFiles)
{
ConvertToTargetFormat(wavFile);
}
byte[] buffer = new byte[1024 * 4];
WaveFileWriter waveFileWriter = null;
try
{
foreach (string wavFile in wavFiles)
{
using (var reader = new WaveFileReader(wavFile))
{
if (waveFileWriter == null)
{
waveFileWriter = new WaveFileWriter(outputFilePath, reader.WaveFormat);
}
else
{
if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
{
throw new InvalidOperationException($"Unexpected different wave format in file {wavFile} after conversion.");
}
}
int bytesRead;
while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
waveFileWriter.Write(buffer, 0, bytesRead);
}
}
}
}
finally
{
waveFileWriter?.Dispose();
}
}
private void ConvertToTargetFormat(string wavFilePath)
{
using (var reader = new AudioFileReader(wavFilePath))
{
if (reader.WaveFormat.SampleRate == targetFormat.SampleRate &&
reader.WaveFormat.BitsPerSample == targetFormat.BitsPerSample &&
reader.WaveFormat.Channels == targetFormat.Channels)
{
return;
}
string tempFile = Path.Combine(Path.GetDirectoryName(wavFilePath),
Path.GetFileNameWithoutExtension(wavFilePath) + "_temp.wav");
using (var resampler = new MediaFoundationResampler(reader, targetFormat))
{
resampler.ResamplerQuality = 60;
WaveFileWriter.CreateWaveFile(tempFile, resampler);
}
File.Delete(wavFilePath);
File.Move(tempFile, wavFilePath);
}
}
}
}