我在Asp.Net MVC 5框架的顶部使用c#编写了一个应用程序。
我的目标是拨打第三方服务以下载wave文件。然后我想将此文件转换为mp3。最后,我想将mp3文件作为(byte [])返回,以允许用户直接从内存中下载。
以下是我的代码最终会如何允许用户从内存中下载转换后的文件
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");
}
但是我遇到了ConvertToMp3
方法的问题。
我正在使用NAudio库来转换文件转换。这是我到目前为止的代码
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);
}
}
上述方法转换文件。但是这种方法将波形文件写入桌面,将其转换为mp3然后删除波形文件。此外,此方法将mp3文件写入桌面,而不是返回byte[]
内容。
如何在不必写入桌面的情况下将文件转换为内存?另外,如何将mp3文件转换为byte[]
?
答案 0 :(得分:2)
也许是这样的。
注意:完全没有经过测试,我只是看了看来源。
同步强>
public byte[] ConvertToMp3(Uri uri)
{
using (var client = new WebClient())
{
var file = client.DownloadData(uri);
var target = new WaveFormat(8000, 16, 1);
using (var outPutStream = new MemoryStream())
using (var waveStream = new WaveFileReader(new MemoryStream(file)))
using (var conversionStream = new WaveFormatConversionStream(target, waveStream))
using (var writer = new LameMP3FileWriter(outPutStream, conversionStream.WaveFormat, 32, null))
{
conversionStream.CopyTo(writer);
return outPutStream.ToArray();
}
}
}
<强>异步强>
public async Task<byte[]> ConvertToMp3Async(Uri uri)
{
using (var client = new WebClient())
{
var file = await client.DownloadDataTaskAsync(uri);
var target = new WaveFormat(8000, 16, 1);
using (var outPutStream = new MemoryStream())
using (var waveStream = new WaveFileReader(new MemoryStream(file)))
using (var conversionStream = new WaveFormatConversionStream(target, waveStream))
using (var writer = new LameMP3FileWriter(outPutStream, conversionStream.WaveFormat, 32, null))
{
await conversionStream.CopyToAsync(writer);
return outPutStream.ToArray();
}
}
}