Convert MP4 to Ogg with C# - c#

Does anyone know a simple way of converting a mp4 file to an ogg file?
Have to do it, but don't have much knowlegde about it, and all I can find are programs, not examples or libraries.
Thanks in advance

I would recommend dispatching this to FFMPEG - http://www.ffmpeg.org/ - using a Process and command line arguments. You can redirect I/O if you need to (e.g. logging). Just do something like process.WaitForExit() after you've started it. You could do this on a background thread (BackgroundWorker, ThreadPool, etc...) if you need to not block the UI.

Extending Chad's answer I used the NReco.VideoConverter which is a helpful wrapper for FFMPEG. My code to convert a MP4 to OGG is as follows.
1.Save the file to a temporary file in local storage.
var path = Path.GetTempPath() + name;
using (var file = File.Create(path))
{
stream.Seek(0, SeekOrigin.Begin);
await stream.CopyToAsync(file);
file.Close();
return path;
}
2.Now use the video converter to convert the file, simple!
var output = new MemoryStream();
var ffMpeg = new FFMpegConverter();
ffMpeg.ConvertMedia(filePath, output, Format.ogg);
output.Seek(0, SeekOrigin.Begin);
return output;

static void Mp4ToOgg(string fileName)
{
DsReader dr = new DsReader(fileName);
if (dr.HasAudio)
{
string waveFile = fileName + ".wav";
WaveWriter ww = new WaveWriter(File.Create(waveFile),
AudioCompressionManager.FormatBytes(dr.ReadFormat()));
ww.WriteData(dr.ReadData());
ww.Close();
dr.Close();
try
{
Sox.Convert(#"sox.exe", waveFile, waveFile + ".ogg", SoxAudioFileType.Ogg);
}
catch (SoxException ex)
{
throw;
}
}
}
from How to converts a mp4 file to an ogg file

Related

create zip file in .net with password

I'm working on a project that I need to create zip with password protected from file content in c#.
Before I've use System.IO.Compression.GZipStream for creating gzip content.
Does .net have any functionality for create zip or rar password protected file?
Take a look at DotNetZip (#AFract supplied a new link to GitHub in the comments)
It has got pretty geat documentation and it also allow you to load the dll at runtime as an embeded file.
Unfortunately there is no such functionality in the framework. There is a way to make ZIP files, but without password. If you want to create password protected ZIP files in C#, I'd recommend SevenZipSharp. It's basically a managed wrapper for 7-Zip.
SevenZipBase.SetLibraryPath(Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? Environment.CurrentDirectory,
"7za.dll"));
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.Compressing += Compressor_Compressing;
compressor.FileCompressionStarted += Compressor_FileCompressionStarted;
compressor.CompressionFinished += Compressor_CompressionFinished;
string password = #"whatever";
string destinationFile = #"C:\Temp\whatever.zip";
string[] sourceFiles = Directory.GetFiles(#"C:\Temp\YourFiles\");
if (String.IsNullOrWhiteSpace(password))
{
compressor.CompressFiles(destinationFile, sourceFiles);
}
else
{
//optional
compressor.EncryptHeaders = true;
compressor.CompressFilesEncrypted(destinationFile, password, sourceFiles);
}
DotNetZip worked great in a clean way.
DotNetZip is a FAST, FREE class library and toolset for manipulating zip files.
Code
static void Main(string[] args)
{
using (ZipFile zip = new ZipFile())
{
zip.Password = "mypassword";
zip.AddDirectory(#"C:\Test\Report_CCLF5\");
zip.Save(#"C:\Test\Report_CCLF5_PartB.zip");
}
}
I want to add some more alternatives.
For .NET one can use SharpZipLib, for Xamarin use SharpZipLib.Portable.
Example for .NET:
using ICSharpCode.SharpZipLib.Zip;
// Compresses the supplied memory stream, naming it as zipEntryName, into a zip,
// which is returned as a memory stream or a byte array.
//
public MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) {
MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
zipStream.Password = "Your password";
ZipEntry newEntry = new ZipEntry(zipEntryName);
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
zipStream.CloseEntry();
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream.
outputMemStream.Position = 0;
return outputMemStream;
// Alternative outputs:
// ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory.
byte[] byteArrayOut = outputMemStream.ToArray();
// GetBuffer returns a raw buffer raw and so you need to account for the true length yourself.
byte[] byteArrayOut = outputMemStream.GetBuffer();
long len = outputMemStream.Length;
}
More samples can be found here.
If you can live without password functionality, one can mention ZipStorer or the built in .NET function in System.IO.Compression.

How to decompress zip with password in windows 8 metro program?

I have a zip password file and know this password.
I need open this zip file in Windows 8 metro app program code.
But 'System.IO.Compression.ZipArchive' is not supported decompress zip with password in Windows 8 metro app program code.
I'm try SharpZipLib and DotNetZip. BUT they are not support net 4.5. So i doesn't use them in my metro program code.
I'm try Ionic.Zip. It's ok in program code. I want to build packages to upload to the windows store. But not pass in microsoft code review.
Is there another way?
thanks a lot
The System.IO.Compression.FileSystem assembly is not available for Windows Store apps, so you cannot use the ExtractToDirectory extension method of the ZipFileExtensions class.
Instead of DirectoryInfo, FileInfo, etc. use StorageFile. See Accessing data and files and the File access sample for more information on how to read and write files in Metro style apps. Then you'll need to read the data from the file into a stream and then pass that to methods of one of the following class (your choice):
DeflateStream (which internally uses zlib as of .NET 4.5)
ZipArchive or GZipStream classes. Those are available to Metro style apps, even if the file specific extension methods are not.
Windows Runtime type Decompressor to decompress files.
you can using https://sharpcompress.codeplex.com/.
it support open file zip have password
code bellow
//if file zip have a file pdf , a file xml
async void Read(StorageFile file)
{
MemoryStream memoryFilePDf = new MemoryStream();
MemoryStream memoryFileXml = new MemoryStream();
FilePdf = null;
FileXml = null;
using (var zipStream = await file.OpenStreamForReadAsync())
{
using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
{
await zipStream.CopyToAsync(zipMemoryStream);
try
{
using (var archive = ZipArchive.Open(zipMemoryStream, PassWord))
{
bool isFilePdf = false;
foreach (var entry in archive.Entries)
{
if (!entry.Key.ToLower().EndsWith(".pdf") && !entry.Key.ToLower().EndsWith(".xml"))
{
continue;
}
if (entry.Key.ToLower().EndsWith(".pdf"))
{
isFilePdf = true;
entry.WriteTo(memoryFilePDf);
}
else
{
isFilePdf = false;
entry.WriteTo(memoryFileXml);
}
var fileName = entry.Key.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
var createFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);
using (IRandomAccessStream stream = await createFile.OpenAsync(FileAccessMode.ReadWrite))
{
// Write compressed data from memory to file
using (Stream outstream = stream.AsStreamForWrite())
{
byte[] buffer = isFilePdf ? memoryFilePDf.ToArray() : memoryFileXml.ToArray();
outstream.Write(buffer, 0, buffer.Length);
outstream.Flush();
}
}
if (isFilePdf)
{
FilePdf = createFile;
}
else
{
FileXml = createFile;
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}

Convert .db to binary

I'm trying to convert a .db file to binary so I can stream it across a web server. I'm pretty new to C#. I've gotten as far as looking at code snippets online but I'm not really sure if the code below puts me on the right track. How I can write the data once I read it? Does BinaryReader automatically open up and read the entire file so I can then just write it out in binary format?
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream("output.bin", FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
long totalBytes = new System.IO.FileInfo("input.db").Length;
byte[] buffer = null;
BinaryReader binReader = new BinaryReader(File.Open("input.db", FileMode.Open));
}
}
}
}
Edit: Code to stream the database:
[WebGet(UriTemplate = "GetDatabase/{databaseName}")]
public Stream GetDatabase(string databaseName)
{
string fileName = "\\\\computer\\" + databaseName + ".db";
if (File.Exists(fileName))
{
FileStream stream = File.OpenRead(fileName);
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "binary/.bin";
}
return stream;
}
return null;
}
When I call my server, I get nothing back. When I use this same type of method for a content-type of image/.png, it works fine.
All the code you posted will actually do is copy the file input.db to the file output.bin. You could accomplish the same using File.Copy.
BinaryReader will just read in all of the bytes of the file. It is a suitable start to streaming the bytes to an output stream that expects binary data.
Once you have the bytes corresponding to your file, you can write them to the web server's response like this:
using (BinaryReader binReader = new BinaryReader(File.Open("input.db",
FileMode.Open)))
{
byte[] bytes = binReader.ReadBytes(int.MaxValue); // See note below
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
Response.End();
}
Note: The code binReader.ReadBytes(int.MaxValue) is for demonstrating the concept only. Don't use it in production code as loading a large file can quickly lead to an OutOfMemoryException. Instead, you should read in the file in chunks, writing to the response stream in chunks.
See this answer for guidance on how to do that
https://stackoverflow.com/a/8613300/141172

change wav file ( to 16KHz and 8bit ) with using NAudio

I want to change a WAV file to 8KHz and 8bit using NAudio.
WaveFormat format1 = new WaveFormat(8000, 8, 1);
byte[] waveByte = HelperClass.ReadFully(File.OpenRead(wavFile));
Wave
using (WaveFileWriter writer = new WaveFileWriter(outputFile, format1))
{
writer.WriteData(waveByte, 0, waveByte.Length);
}
but when I play the output file, the sound is only sizzle. Is my code is correct or what is wrong?
If I set WaveFormat to WaveFormat(44100, 16, 1), it works fine.
Thanks.
A few pointers:
You need to use a WaveFormatConversionStream to actually convert from one sample rate / bit depth to another - you are just putting the original audio into the new file with the wrong wave format.
You may also need to convert in two steps - first changing the sample rate, then changing the bit depth / channel count. This is because the underlying ACM codecs can't always do the conversion you want in a single step.
You should use WaveFileReader to read your input file - you only want the actual audio data part of the file to get converted, but you are currently copying everything including the RIFF chunks as though they were audio data into the new file.
8 bit PCM audio usually sounds horrible. Use 16 bit, or if you must have 8 bit, use G.711 u-law or a-law
Downsampling audio can result in aliasing. To do it well you need to implement a low-pass filter first. This unfortunately isn't easy, but there are sites that help you generate the coefficients for a Chebyshev low pass filter for the specific downsampling you are doing.
Here's some example code showing how to convert from one format to another. Remember that you might need to do the conversion in multiple steps depending on the format of your input file:
using (var reader = new WaveFileReader("input.wav"))
{
var newFormat = new WaveFormat(8000, 16, 1);
using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))
{
WaveFileWriter.CreateWaveFile("output.wav", conversionStream);
}
}
The following code solved my problem dealing with G.711 Mu-Law with a vox file extension to wav file. I kept getting a "No RIFF Header" error with WaveFileReader otherwise.
FileStream fileStream = new FileStream(fileName, FileMode.Open);
var waveFormat = WaveFormat.CreateMuLawFormat(8000, 1);
var reader = new RawSourceWaveStream(fileStream, waveFormat);
using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader))
{
WaveFileWriter.CreateWaveFile(fileName.Replace("vox", "wav"), convertedStream);
}
fileStream.Close();
openFileDialog openFileDialog = new openFileDialog();
openFileDialog.Filter = "Wave Files (*.wav)|*.wav|All Files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
WaveFileReader reader = new NAudio.Wave.WaveFileReader(dpmFileDestPath);
WaveFormat newFormat = new WaveFormat(8000, 16, 1);
WaveFormatConversionStream str = new WaveFormatConversionStream(newFormat, reader);
try
{
WaveFileWriter.CreateWaveFile("C:\\Konvertierten_Dateien.wav", str);
}
catch (Exception ex)
{
MessageBox.Show(String.Format("{0}", ex.Message));
}
finally
{
str.Close();
}
MessageBox.Show("Konvertieren ist Fertig!");
}

What is C# for C " FILE *f;"?

I am a beginner in C#
I wonder how to write in C# C's
static void example(const char *filename)
{
FILE *f;
outbuf_size = 10000;
outbuf = malloc(outbuf_size);
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "could not open %s\n", filename);
exit(1);
}
fwrite(outbuf, 1, outbuf_size, f);
fclose(f);
}
Plase help.
BTW: Well I am trying to port FFMPEG api-example presented here using Tao.FFMpeg (Tao is .Net wrapper around C#.. old and with sintax exact as in FFMPEG itself) so could you please read that one and tell what I missed in my code sample...
My problem is - I understand how to port FFMpeg part and I just do not det how to port File IO part\function in the way good for .Net
Rather than writing all of the code for you, I'm going to direct you to System.IO.File.
Well, since the sample code of the library you provided reads and writes binary files, I'd suggest System.IO.BinaryReader and System.IO.BinaryWriter.
static void example(string filename)
{
StreamReader sr;
BinaryWriter bw;
try
{
sr = new StreamReader(filename);
bw = new BinaryWriter(File.Open("out.bin", FileMode.Create));
bw.Write(sr.ReadToEnd());
bw.Flush();
bw.Close();
sr.Close();
}
catch(Exception ex)
{
// Handle the exception
}
}
Your code sample is confusing. Either you mean to put something meaningful in the buffer and write it to the file, or you mean to read from the file into the buffer.
using System.IO;
byte[] bytesFromFile = File.ReadAllBytes(filePath);
byte[] someBytes = new byte[someLength];
// omitted: put some values into someBytes array
File.WriteAllBytes(filePath, someBytes);
Take a look at the following namespace System.IO. Specifically you will want to look at System.IO.File and also System.IO.FileStream
See FileStream.WriteByte help. There is an example.

Categories

Resources