Using SharpFFmpeg.dll for video conversion - c#

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.

Related

Image uploading in images folder issue in Asp.net

I am trying to upload JPG file to a folder I have created in my project.
The image does not get saved in the images folder. It displays my image when I upload but the image itself is not present in images folder.
Here is the code i am using:
private void btnUpload_Click(object sender, System.EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
// Set constant values
sSavePath = "images/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;
// If file field isn’t empty
if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}
// 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;
}
// 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();
// Check whether the file is really a JPEG by opening it
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
// If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}
// Save thumbnail and output it onto the webpage
System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
imgPicture.ImageUrl = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Text = "File uploaded successfully!";
// Destroy objects
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}
public bool ThumbnailCallback()
{
return false;
}
I'd be surprised if the line myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); works...
You are trying to map a file which doesn't exist yet!
Try
myThumbnail.Save(Server.MapPath(sSavePath) + sThumbFile));

Read Image file metadata

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;
}

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

Azure storage, can not upload images correctly

I am trying to create a action, in a mvc project. that can upload files and images to my azure storage. but for some reason will it just not upload corrently, that is what i am guessing.
If i upload the image with "Azure Storage Explorere" dose it work fine.
Example: http://storage.sogaard.us/company1/wallpaper-396234.jpg
But if i try to upload the image though my action will it not work, it send a 200 for succes and the right conten type, but the image will not load, and my developer tool tells me i got not data from the server.
Example: http://storage.sogaard.us/company1/b9206edac188e1d8aa2b3be7cdc4b94a.jpg
I have tried to save the uploaded til to my local computer instead of the azure storage and it worked fine there! I can simply not find the reason and this have been bugging me all day :(
Here is my code
[HttpPost]
public ActionResult Upload(FilesUploadModel model, IEnumerable<HttpPostedFileBase> files)
{
if(ModelState.IsValid)
{
if (files != null && files.Any())
{
int maxSizeInBytes = ConfigurationManager.Instance.Configuration.FileMaxSize;
Size thumbSize = new Size(200, 200);
foreach (HttpPostedFileBase file in files.Where(x => x != null))
{
CMS.Common.Data.File _file = new Sogaard.Inc.CMS.Common.Data.File();
// is any files uploadet?
if (!(file.ContentLength > 0))
{
FlashHelper.Add(Text("File not received"), FlashType.Error);
continue;
}
// is the file larger then allowed
if (file.ContentLength > maxSizeInBytes)
{
FlashHelper.Add(Text("The file {0}'s file size was larger then allowed", file.FileName), FlashType.Error);
continue;
}
var fileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now) + Path.GetExtension(file.FileName);
string mimeType = FileHelper.MimeType(FileHelper.GetMimeFromFile(file.InputStream));
_file.SiteId = SiteId();
_file.Container = GetContainerName();
_file.FileName = Path.GetFileName(file.FileName);
_file.FileNameServer = fileName;
_file.Created = DateTime.Now;
_file.Folder = model.Folder;
_file.Size = file.ContentLength;
_file.Type = mimeType;
if (mimeType.ToLower().StartsWith("image/"))
{
try
{
// So we don't lock the file
using (Bitmap bitmap = new Bitmap(file.InputStream))
{
_file.Information = bitmap.Width + "|" + bitmap.Height;
if (bitmap.Height > 500 && bitmap.Width > 500)
{
var thumbfileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + "thumb" + DateTime.Now) + ".jpeg";
Size thumbSizeNew = BaseHelper.ResizeImage(bitmap.Size, thumbSize);
Bitmap thumbnail = (Bitmap)bitmap.GetThumbnailImage(thumbSizeNew.Width,
thumbSizeNew.Height,
ThumbnailCallback,
IntPtr.Zero);
_file.ThumbFileNameServer = thumbfileName;
// Retrieve reference to a blob named "myblob"
CloudBlob blob = container().GetBlobReference(_file.ThumbFileNameServer);
blob.Metadata["Filename"] = Path.GetFileNameWithoutExtension(file.FileName) + "-thumb" + ".jpg";
blob.Properties.ContentType = "image/jpeg";
// Create or overwrite the "myblob" blob with contents from a local file
using (MemoryStream memStream = new MemoryStream())
{
thumbnail.Save(memStream, ImageFormat.Jpeg);
blob.UploadFromStream(memStream);
}
blob.SetMetadata();
blob.SetProperties();
}
}
}
catch (Exception e)
{
if (e.GetType() != typeof (DataException))
FlashHelper.Add(Text("The image {0} was not a valid image", file.FileName),
FlashType.Error);
// Removing the file
System.IO.File.Delete(file.FileName);
}
}
else
{
_file.Information = null;
}
// Retrieve reference to a blob named "myblob"
CloudBlob blobF = container().GetBlobReference(fileName);
blobF.Metadata["Filename"] = file.FileName;
blobF.Properties.ContentType = mimeType;
// Create or overwrite the "myblob" blob with contents from a local file
blobF.UploadFromStream(file.InputStream);
blobF.SetMetadata();
blobF.SetProperties();
fileService.Save(_file);
}
}
return RedirectToAction("Display", new { Folder = model.Folder });
}
model.FolderSugestion = fileService.GetFolders(SiteId());
return View(model);
}
private CloudBlobContainer container()
{
// Retrieve storage account from connection-string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Create the blob client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container
var container = blobClient.GetContainerReference(GetContainerName());
container.CreateIfNotExist();
return container;
}
private string GetContainerName()
{
return "company" + SiteId();
}
In the thumbnail code path, I think you need memStream.Position = 0 to reset the stream back to the beginning before trying to upload it.
For the other (non-image) code path, nothing stands out as wrong. Does that code work?
In both code paths, you don't need blob.SetMetadata() and blob.SetProperties(), since those will be done when the upload happens.
[EDIT] Also, what does GetMimeFromFile do? Does it read from the stream (thus perhaps leaving the stream position somewhere other than the beginning)?

Mixing and converting wav files to one mp3 file

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?

Categories

Resources