Last time, I encountered a need to merge multiple audio files in the project. I searched the internet and found something written by a foreigner. It is now posted on the homepage. Dudu can be removed if he finds it hard.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. IO;
Using system. runtime. interopservices;
Namespace mergewaves
{
Public class waveio
{
Public int length;
Public short channels;
Public int samplerate;
Public int datalength;
Public short bitspersample;
Private void waveheaderin (string Spath)
{
Filestream FS = new filestream (Spath, filemode. Open, fileaccess. Read );
Binaryreader BR = new binaryreader (FS );
Length = (INT) fs. Length-8;
FS. Position = 22;
Channels = Br. readint16 ();
FS. Position = 24;
Samplerate = Br. readint32 ();
FS. Position = 34;
Bitspersample = Br. readint16 ();
Datalength = (INT) fs. Length-44;
BR. Close ();
FS. Close ();
}
Private void waveheaderout (string Spath)
{
Filestream FS = new filestream (Spath, filemode. Create, fileaccess. Write );
Binarywriter BW = new binarywriter (FS );
FS. Position = 0;
Bw. Write (New char [4] {'R', 'I', 'F', 'F '});
Bw. Write (length );
BW. write (New char [8] {'w', 'A', 'V', 'E', 'F', 'M','t ', ''});
Bw. Write (INT) 16 );
Bw. Write (short) 1 );
Bw. Write (channels );
Bw. Write (samplerate );
Bw. Write (INT) (samplerate * (bitspersample * channels)/8 )));
Bw. Write (short) (bitspersample * channels)/8 ));
Bw. Write (bitspersample );
Bw. Write (New char [4] {'D', 'A', 't', 'A '});
Bw. Write (datalength );
Bw. Close ();
FS. Close ();
}
Public void Merge (string [] files, string OUTFILE)
{
Waveio wa_in = new waveio ();
Waveio wa_out = new waveio ();
Wa_out.datalength = 0;
Wa_out.length = 0;
// Gather header data
Foreach (string path in files)
{
Wa_in.waveheaderin (@ path );
Wa_out.datalength + = wa_in.datalength;
Wa_out.length + = wa_in.length;
}
// Recontruct new Header
Wa_out.bitspersample = wa_in.bitspersample;
Wa_out.channels = wa_in.channels;
Wa_out.samplerate = wa_in.samplerate;
Wa_out.waveheaderout (@ OUTFILE );
Foreach (string path in files)
{
Filestream FS = new filestream (@ path, filemode. Open, fileaccess. Read );
Byte [] arrfile = new byte [fs. Length-44];
FS. Position = 44;
FS. Read (arrfile, 0, arrfile. Length );
FS. Close ();
Filestream fo = new filestream (@ OUTFILE, filemode. append, fileaccess. Write );
Binarywriter BW = new binarywriter (FO );
Bw. Write (arrfile );
Bw. Close ();
Fo. Close ();
}
}
}
}
You can call the merge method directly. The first parameter is the sound array to be merged, and the second parameter is the output path.