I have an application written using c# on the top of Asp.Net MVC 5 framework.
My objective is to make a call to 3rd party service to download a wave file. Then I want to convert this file into mp3. Finally, I want to return the mp3 file as (byte[]) to allow the user to download it directly from memory.
Here is how my code will end up which allow the user to download the converted file from the memory
public ActionResult Download(int? id)
{
// Download and convert the file
// the variable "someUri" is generated based on the provided id value
byte[] filedata = ConvertToMp3(someUri);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "filename.mp3",
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, "audio/mpeg");
}
But I am having issue with the ConvertToMp3
method.
I am using NAudio library to convert the file conversion. Here is my code so far
public void ConvertToMp3(Uri uri)
{
using (var client = new WebClient())
{
byte[] file = client.DownloadData(uri);
string wavFileFullName = GetFullDirectory() + "filename.wav";
string mp3FileFullName = GetFullDirectory() + "filename.mp3";
WaveFormat target = new WaveFormat(8000, 16, 1);
using (WaveStream stream = new WaveFileReader(new MemoryStream(file)))
using (WaveFormatConversionStream str = new WaveFormatConversionStream(target, stream))
{
WaveFileWriter.CreateWaveFile(wavFileFullName, str);
using (var reader = new WaveFileReader(wavFileFullName))
using (var writer = new LameMP3FileWriter(mp3FileFullName, reader.WaveFormat, bitRate))
{
reader.CopyTo(writer);
}
}
File.Delete(wavFileFullName);
}
}
The above method converts the file. But this method writes the wave file to desk, converts it to mp3 then delete the wave file. Additionally this method writes the mp3 file to the desk instead of returning byte[]
content.
How can I convert the file in memory without having to write to desk? Also, how can I convert the mp3 file to byte[]
?