首先我調用了微信接口,錄完得音頻文件後調用微信的上傳錄音接口把本地錄音先上傳到微信的服務器,不過,微信只保留3天,而我們需要長期保存,我們需要把資源從微信服務器下載到自己的服務器,這時調用微信的下載多媒體接口(即官方文檔獲取臨時素材接口)下載到自己服務器, 注意這個接口下載的音頻是amr格式,HTML不支持amr格式的音頻,需要轉成MP3格式的文件。我自己就被這個格式坑了 用audio 播放不了 轉成MP3就好了
網上有用第三方軟件的:ffmpeg ,而我引用的NReco.VideoConverter.dll 這個其實是對ffmpeg 封裝的包
1、打開管理NuGet程序包進行安裝NReco.VideoConverter.dll
2、代碼
using NReco.VideoConverter;
/// <summary>
/// 格式轉化
/// </summary>
/// <param name="inputFile">源文件路徑</param>
/// <param name="inputFormat">源文件格式</param>
/// <param name="outFile">轉化後文件路徑</param>
/// <param name="outFormat">轉化後文件格式</param>
public static void FormatConversion(string inputFile, string inputFormat, string outFile, string outFormat, int audioSampleRate = 44100)
{
try
{
new FFMpegConverter().ConvertMedia(inputFile, inputFormat, outFile, outFormat, new ConvertSettings { AudioSampleRate = audioSampleRate });
}
catch (Exception ex)
{
throw ex;
// ignored
}
}
public JsonResult GetMultimedia()
{
string file = string.Empty;
string content = string.Empty;
string strpath = string.Empty;
string savepath = string.Empty;
var appId = WeixinConfig.AppID;
var appSecret = WeixinConfig.AppSecret;
var access_token = "";
using (CommanderServiceClient client = new CommanderServiceClient())
{
access_token = client.GetAccessToken(appId, appSecret, false);
}
var media_id =Request["serverId"];
string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + media_id;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
strpath = myResponse.ResponseUri.ToString();
LogWriter.Default.WriteInfo("接收類別://" + myResponse.ContentType);
WebClient mywebclient = new WebClient();
savepath = Server.MapPath("/Files/weixinVoice") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + ".amr";
LogWriter.Default.WriteInfo("路徑://" + savepath);
try
{
mywebclient.DownloadFile(strpath, savepath);
var newfile = savepath.Replace(".amr",".mp3");
LogWriter.Default.WriteInfo("新路徑://" + newfile);
FormatConversion(savepath, "amr", newfile, "mp3");
//成功返回文件名稱
file = System.IO.Path.GetFileName(newfile);
}
catch (Exception ex)
{
LogWriter.Default.WriteError("GetMultimedia=>" + ex.Message);
}
}
return Json(file);
}