如何阅读.mp3音频文件? 我写了下面的代码。
public static byte[] ReadFully(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
它接受.3gp,.caf foramat流。为什么它不接受.mp3文件? }
答案 0 :(得分:1)
我使用以下代码从我的REST WCF服务下载mp3文件:
[WebGet]
public Stream GetMp3()
{
byte[] buffer;
WebOperationContext.Current.OutgoingResponse.ContentType = "audio/mp3";
using (FileStream ms = new FileStream(@"C:\Sample.mp3", FileMode.Open))
{
int length = (int)ms.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
buffer = new byte[length];
int sum = 0;
int count;
while ((count = ms.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
ms.Close();
}
return new MemoryStream(buffer);
}
更新:将mp3文件上传到Restful WCF服务
服务器端方法:
[WebInvoke]
public string RecieveMp3(Stream mp3Stream)
{
byte[] buffer = new byte[5000000];
using (FileStream ms = new FileStream("C:\\Temp\\Test1.mp3", FileMode.OpenOrCreate))
{
int read = mp3Stream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, read);
}
return "Recieved Mp3 file";
}
注意: 1.确保您对该文件夹具有权限,以便为与运行wcf服务的应用程序池关联的用户编写mp3文件 2.出于测试目的,我已将字节数组大小硬编码为较大的值。
客户致电服务:
private string UseRestSharpApproachForFiles(string serviceBaseUrl, string resourceUrl, Method method, string filepath)
{
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method) { DateFormat = DataFormat.Xml.ToString(), Resource = resourceUrl };
request.AddFile("stream", filepath);
var response = client.Execute(request);
string responseString;
if (response.StatusCode == HttpStatusCode.OK)
{
responseString = HttpUtility.HtmlDecode(response.Content);
}
else
{
responseString = response.StatusDescription + " --------------------" + HttpUtility.HtmlDecode(response.Content);
}
return responseString;
}
使用第三方dll调用名为RestSharp的休息服务。