Mixing and converting wav files to one mp3 file - c#

I have 2 wav files. It should convert them to one mp3 file using naudio and lame.exe. Note that the wav file should be created by mixing 2 wav files (not concatenating).
two wav files => one mp3 file
private void MixWavFiles(string[] inputFiles, string outFileName)
{
int count = inputFiles.GetLength(0);
WaveMixerStream32 mixer = new WaveMixerStream32();
WaveFileReader[] reader = new WaveFileReader[count];
WaveChannel32[] channelSteam = new WaveChannel32[count];
mixer.AutoStop = true;
for (int i = 0; i < count; i++)
{
reader[i] = new WaveFileReader(inputFiles[i]);
channelSteam[i] = new WaveChannel32(reader[i]);
mixer.AddInputStream(channelSteam[i]);
}
mixer.Position = 0;
WaveFileWriter.CreateWaveFile(outFileName, mixer);
}
private string ConvertWavToMp3(string wavFileName)
{
string mp3FileName = Path.ChangeExtension(wavFileName, "mp3").Replace(Directory.GetCurrentDirectory(), "c:");
string commandLine = " -V2 " + wavFileName + " " + mp3FileName;
var lamaProcessInfo = new ProcessStartInfo();
lamaProcessInfo.Arguments = commandLine;
lamaProcessInfo.FileName = WavToMp3ConverterFileName;
lamaProcessInfo.WindowStyle = ProcessWindowStyle.Minimized;
using (var lamaProcess = Process.Start(lamaProcessInfo))
{
lamaProcess.WaitForExit();
int exitCode = lamaProcess.ExitCode;
lamaProcess.Close();
}
return mp3FileName;
}
Well, my this is how I'm doing that:
First I'm mixing 2 wav files using NAudio and getting one mixed wav
file.
Then I'm converting this wav file to mp3 file using lame.exe.
At the second step exitCode always equals 1 and it means there is an error. So I'm unable to convert wav file (mixed) to mp3 (result) file.
But if I'm converting each of two wav files to two mp3 files it works fine! And exitCode equals 0. So I have a conclusion the commandLine for converting one (mixed) wav file to mp3 file is wrong. Or the mixed wav has the wrong format but it's not most likely because it can be played by winamp.
Does anyone have any suggestions?

Related

create textfile dynamically if textfile size exceeds maximum size

I'm writing text to files using StreamWriter using the following code:
path == #"Desktop\";
filepath1 = path + "1.txt";
StreamWriter _sw = new StreamWriter(filepath1, true);
_sw.WriteLine("some Text");
_sw.Close();
if size of textfile exceeds 500kb I want to create text files dynamically. I'm tryng following code:
var size = (path.Length)/1024;
if(size>=500)
{
int i = (size/500)+1;
var filepath2 = path + i + ".txt";
if (File.Exists(filepath2))
{
StreamWriter _sw = new StreamWriter(filepath2, true);
_sw.WriteLine("Some message");
_sw.Close();
}
}
else
{
FileStream fs = File.Create(filepath2);
StreamWriter _sw = new StreamWriter(filepath2, true);
_sw.WriteLine(ex);
_sw.Close();
}
My question is if file 2.txt also exceeds 500kb I want to create 3.txt,4.txt..... and so on..
I want to create all these dynamically - how to solve this problem?
First thing you need to do the SIZE comparison for the data length of File not the File Path.
Here is Function which dose what you want to achieve, Please make appropriate changes for your path.
//Public variable to manage file names
int FileCounter = 1;
string FileName;
// Call this function to Add text to file
private void WriteToFile(string writeText)
{
FileName = "MyFile_"+FileCounter +".txt";
if (File.Exists(FileName))
{
string str = File.ReadAllText(FileName);
if ((str.Length + writeText.Length) / 1024 > 500) // check for limit
{
// Create new File
FileCounter++;
FileName = "MyFile_" + FileCounter + ".txt";
StreamWriter _sw = new StreamWriter(FileName, true);
_sw.WriteLine(writeText);
_sw.Close();
}
else // use exixting file
{
StreamWriter _sw = new StreamWriter(FileName, true);
_sw.WriteLine(writeText);
_sw.Close();
}
}
}
Where to start..
You are writing it as one big long procedural script. You need to break it down into chunks that can be reused using functions. As it is, it will get out of control way too quickly.
path == #"Desktop\"; is not valid. 1 too many =
Use Path.Combine() to combine your folder and filenames.
I'm sure this is all just test/rough/scratch code but just in case it's not, also check out Try/Except to wrap your file handling. You should also look up using() to dispose of your streams/writers.
My last comment would be that I see a lot of this sort of code a lot and it's often replaceable with something like Nlog for a whole lot less friction.
I would have commented but this login has no rep.

sfx files do extract though input the wrong password

I have sfx files from the program that I created using sevenzipsharp library. still when I execute directly with double-click the file sfx if using the wrong password but still extract the files in it with a size of 0 bytes, if anyone should I add another mode to function 'Compress' so that when I execute the file sfx wrong password files are not extracted at all.
Compress code:
public void Compress()
{
SevenZipCompressor.SetLibraryPath("7z.dll");
SevenZipCompressor cmp = new SevenZipCompressor();
cmp.Compressing += new EventHandler<ProgressEventArgs>(cmp_Compressing);
cmp.FileCompressionStarted += new EventHandler<FileNameEventArgs>(cmp_StartCompress);
cmp.CompressionFinished += new EventHandler<EventArgs>(cmp_CompleteCompressed);
cmp.ArchiveFormat = OutArchiveFormat.SevenZip;
cmp.CompressionLevel = CompressionLevel.Normal;
cmp.CompressionMethod = CompressionMethod.Lzma;
cmp.CompressionMode = CompressionMode.Create;
string password = txtPasswordEn.Text;
string DirFile = tempFolder;
string NameFileCompress = Path.Combine(txtOutputFileEn.Text, txtNameFile.Text) + (".zip");
cmp.BeginCompressDirectory(DirFile, NameFileCompress, password, ".",true);
}
Create SFX Code:
public void CreateSfx()
{
string location = Path.Combine(txtOutputFileEn.Text, txtNameFile.Text);
string nameZip = location + (".zip");
string nameExe = location + (".exe");
SfxModule mdl = SfxModule.Extended;
SevenZipSfx sfx = new SevenZipSfx(mdl);
sfx.ModuleFileName = #"7z.sfx";
sfx.MakeSfx(nameZip, nameExe);
}
I've just seen that you're not creating a .zip file but a .7z file (and then convert it to a self extracting archive).
For that file format, you can achieve file name encryption using the EncryptHeaders property:
cmp.EncryptHeaders = true;

C# - Copy File to new location, then read in PDF (With Code)

In the code below, the console prompts the user for 2 files (currently in a networked location). It then copies those files to the local drive for quicker reading of the PDF, but I'm running into a problem. If I reference the last line of code as PdfDocument pdf = new PdfDocument("C:\somepdf.pdf"); the file is accessed extremely quickly.
However, with the current copy processes, for some reason, this line of code alone is taking upwards of 18-20 minutes to process. I'm assuming that this is because the file, having recently been copied, is still locked under a process, even though the actual copy process takes less than 10 seconds.
In my research, I have seen various ways of identifying the process that's locking the file and killing it, but this doesn't seem to apply to what I'm trying to do.
Unfortunately, I'm to the point where I have to ask for help. Am I overlooking something here? I don't see why it would take 15 less minutes to process a pdf referenced locally, than one processed by a copy process, then locally.
Thoughts?
string selectFileNameO;
string selectFileNameF;
string FileNameO;
string FileNameF;
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Title = "Choose File";
dialog.FileName = "";
dialog.ShowDialog();
selectFileNameO = dialog.FileName;
}
string ext = System.IO.Path.GetExtension(selectFileNameO);
selectFileNameF = Path.GetFileName(selectFileNameO);
selectFileNameF = selectFileNameF.Substring(0, selectFileNameF.Length - ext.Length);
selectFileNameF = "C:\\" + selectFileNameF + ".ext";
Console.WriteLine(selectFileNameF);
using (OpenFileDialog dialog2 = new OpenFileDialog())
{
dialog2.Title = "Choose 2 File";
dialog2.FileName = "";
dialog2.ShowDialog();
FileNameO = dialog2.FileName;
}
string ext1 = System.IO.Path.GetExtension(FileNameO);
FileNameF = Path.GetFileName(FileNameO);
FileNameF = FileNameF.Substring(0, FileNameF.Length - ext1.Length);
FileNameF = "C:\\" + FileNameF + ".ext";
File.Copy(FileNameO, FileNameF, true);
int distanceToString = 535;
int lengthOfString = 6;
string myDataSet;
using (StreamReader sr = new StreamReader(selectFileNameF))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
myDataSet = line.Substring(distanceToString, lengthOfString);
selectFileUIDs.Add(myDataSet);
Console.WriteLine(myDataSet);
}
sr.Dispose();
}
Console.WriteLine(FileNameF);
PdfDocument pdf = new PdfDocument(FileNameF);

How split mp3 using Naudio?

How can i cut a certain time of mp3 file and convert it to wave with N audio with out save any file in hard disk? (i want result in byte array!)
Refer Following Code:
string nMP3Folder = "FOLDER PATH";
string nMP3SourceFilename = "SOURCE MP3 FILENAME";
string nMP3OutputFilename = "YOUR OUTPUT MP3 FILENAME";
using (Mp3FileReader rdr = new Mp3FileReader(nMP3Folder + nMP3SourceFilename))
{
int count = 1;
Mp3Frame objmp3Frame = reader.ReadNextFrame();
System.IO.FileStream _fs = new System.IO.FileStream(nMP3Folder + nMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
while (objmp3Frame != null)
{
if (count > 500) //retrieve a sample of 500 frames
return;
_fs.Write(objmp3Frame.RawData, 0, objmp3Frame.RawData.Length);
count = count + 1;
objmp3Frame = rdr.ReadNextFrame();
}
_fs.Close();
}
Also refer following question to get more links:
Trim an MP3 Programatically

Using SharpFFmpeg.dll for video conversion

In my c# application , i am using SharpFFMpeg.dll library for storing video and image files.
And the video files we upload from flex application, which supports flv and some few format of videos only.So when some one upload any type of video format, we planned to convert it into flv.
Before we store the data in database we convert the uploaded file to .tmp file (setting hashcode of uploaded file and adding extension as .tmp) and store temporarily this file in internetcache, as below.
string filename = element.Filename;
string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
// if the internet path doesn't exist, assume mono and /var/tmp
string path = string.IsNullOrEmpty(internetCache)
? Path.Combine("var", "tmp")
: Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");
element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");
And while checking the type of file is written as below.
IntPtr pFormatContext;
FFmpeg.av_register_all();
int ret;
ret = FFmpeg.av_open_input_file(out pFormatContext, this.Filename, IntPtr.Zero, 0, IntPtr.Zero);
if (ret < 0)
{
Trace.WriteLine("couldn't open input file");
FFmpeg.av_free_static();
return;
}
try
{
ret = FFmpeg.av_find_stream_info(pFormatContext);
if (ret < 0)
{
Trace.WriteLine("couldnt find stream informaion");
FFmpeg.av_close_input_file(pFormatContext);
FFmpeg.av_free_static();
return;
}
FFmpeg.AVFormatContext formatContext = (FFmpeg.AVFormatContext)Marshal.PtrToStructure(pFormatContext, typeof(FFmpeg.AVFormatContext));
Duration = formatContext.duration / FFmpeg.AV_TIME_BASE;
for (int i = 0; i < formatContext.nb_streams; ++i)
{
FFmpeg.AVStream stream = (FFmpeg.AVStream)Marshal.PtrToStructure(formatContext.streams[i], typeof(FFmpeg.AVStream));
FFmpeg.AVCodecContext codec = (FFmpeg.AVCodecContext)Marshal.PtrToStructure(stream.codec, typeof(FFmpeg.AVCodecContext));
if (codec.codec_type == FFmpeg.CodecType.CODEC_TYPE_VIDEO)
{
Height = codec.height;
Width = codec.width;
switch (codec.codec_id)
{
case FFmpeg.CodecID.CODEC_ID_FLV1:
case FFmpeg.CodecID.CODEC_ID_VP6F:
case FFmpeg.CodecID.CODEC_ID_H264:
case FFmpeg.CodecID.CODEC_ID_MPEG4:
Type = FileType.flv;
MimeType = "video/x-flv";
break;
But if i upload like avi the above code is not working.
Please help me in the video conversion, by using the SharpFFMPeg dll.

Categories

Resources