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
Related
I have an existing program that does some processing a .pdf file and splitting it into multiple .pdf files based on looking for barcodes on the pages.
The program uses ImageMagick and C#.
I want to change it from outputting pdfs to outputting tifs. Look for the comment in the code below for where I would guess the change would be made.
I included the ImageMagick tag because someone might offer a commandline option that someone else can help me convert to C#.
private void BurstPdf(string bigPdfName, string targetfolder)
{
bool outputPdf = true; // change to false to output tif.
string outputExtension = "";
var settings = new MagickReadSettings { Density = new Density(200) };
string barcodePng = Path.Combine("C:\TEMP", "tmp.png");
using (MagickImageCollection pdfPageCollection = new MagickImageCollection())
{
pdfPageCollection.Read(bigPdfName, settings);
int inputPageCount = 0;
int outputPageCount = 0;
int outputFileCount = 0;
MagickImageCollection resultCollection = new MagickImageCollection();
string barcode = "";
string resultName = "";
IBarcodeReader reader = new BarcodeReader();
reader.Options.PossibleFormats = new List<BarcodeFormat>();
reader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39);
reader.Options.TryHarder = false;
foreach (MagickImage pdfPage in pdfPageCollection)
{
MagickGeometry barcodeArea = getBarCodeArea(pdfPage);
IMagickImage barcodeImg = pdfPage.Clone();
barcodeImg.ColorType = ColorType.Bilevel;
barcodeImg.Depth = 1;
barcodeImg.Alpha(AlphaOption.Off);
barcodeImg.Crop(barcodeArea);
barcodeImg.Write(barcodePng);
inputPageCount++;
using (var barcodeBitmap = new Bitmap(barcodePng))
{
var result = reader.Decode(barcodeBitmap);
if (result != null)
{
// found a first page because it has bar code.
if (result.BarcodeFormat.ToString() == "CODE_39")
{
if (outputFileCount != 0)
{
// write out previous pages.
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
resultCollection = new MagickImageCollection();
}
barcode = standardizePhysicalBarCode(result.Text);
outputFileCount++;
resultCollection.Add(pdfPage);
outputPageCount = 1;
}
else
{
Console.WriteLine("WARNING barcode is not of type CODE_39 so something is wrong. check page " + inputPageCount + " of " + bigPdfName);
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
else
{
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
if (File.Exists(barcodePng))
{
File.Delete(barcodePng);
}
}
if (resultCollection.Count > 0)
{
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
outputFileCount++;
}
}
}
[EDIT] The above code is what I am using (which some untested modifications) to split a .pdf into other .pdfs. I want to know how to modify this code to output tiffs. I put a comment in the code where I think the change would go.
[EDIT] So encouraged by #fmw42 I just ran the code with the .tif extension enabled. Looks like it did convert to a .tif, but the tif is not compressed. I am surprised that IM just configures the output based on the extension name of the file. Handy I guess, but just seems a little loose.
[EDIT] I figured it out. Although counter-intuitive ones sets the compression on the read of the file. I am reading a .pdf but I set the compression to Group for like this:
var settings = new MagickReadSettings { Density = new Density(200), Compression = CompressionMethod.Group4 };
The thing I learned was that simply naming the output file .tif tells IM to output a tif. That is a handy way to do it, but it just seems sloppy.
I'm creating a software to get the data from .dat file and write those data in database. There are so many .dat files so I need to do a batch process. I'm currently reading one dat file by using this code
UDisk udisk = new UDisk();
byte[] byDataBuf = null;
int iLength;//length of the bytes to get from the data
string sPIN2 = "";
string sVerified = "";
string sTime_second = "";
string sDeviceID = "";
string sStatus = "";
string sWorkcode = "";
openFileDialog1.Filter = "1_attlog(*.dat)|*.dat";
openFileDialog1.FileName = "1_attlog.dat";//1 stands for one possible deviceid
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream stream = new FileStream(openFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
lvSSRAttLog.Items.Clear();
int iStartIndex = 0;
int iOneLogLength;//the length of one line of attendence log
for (int i = iStartIndex; i < iLength - 2; i++)//modify by darcy on Dec.4 2009
{
if (byDataBuf[i] == 13 && byDataBuf[i + 1] == 10)
{
iOneLogLength = (i + 1) + 1 - iStartIndex;
byte[] bySSRAttLog = new byte[iOneLogLength];
Array.Copy(byDataBuf, iStartIndex, bySSRAttLog, 0, iOneLogLength);
udisk.GetAttLogFromDat(bySSRAttLog, iOneLogLength, out sPIN2, out sTime_second, out sDeviceID, out sStatus, out sVerified, out sWorkcode);
ListViewItem list = new ListViewItem();
list.Text = sPIN2;
list.SubItems.Add(sTime_second);
list.SubItems.Add(sDeviceID);
list.SubItems.Add(sStatus);
list.SubItems.Add(sVerified);
list.SubItems.Add(sWorkcode);
lvSSRAttLog.Items.Add(list);
bySSRAttLog = null;
iStartIndex += iOneLogLength;
iOneLogLength = 0;
}
}
stream.Close();
}
How can I read files one by one and transfer those data into database.
My database is - SMS
table is -
CHECKINOUT
columns -CHECKDate datetime
CHECKTime datetime
InOutMode int
Status varchar(50)
WorkCode varchar(50)
Memoinfo varchar(50)
sn int
sn2 int
Ip varchar(16)
Updated int
Given a folder path, you can use Directory.EnumerateFiles to get .dat files one by one:
string folder = #"D:\your\Folder";
foreach(var file in Directory.EnumerateFiles(
folder, // folder path
"*.dat" // file type you want
/*, SearchOption.AllDirectories*/)) // uncomment it if you want open files in subfolder
{
FileStream stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read);
byDataBuf = File.ReadAllBytes(openFileDialog1.FileName);
iLength = Convert.ToInt32(stream.Length);
// Do your stuff here
stream.Close();
}
I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}
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?
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.