Index.cshtml
@
{
Layout
= null;
}
<!DOCTYPE html
>
<html
>
<head
>
<meta name
="viewport" content
="width=device-width" />
<title
>Index
</title
>
<script src
="~/Scripts/jquery-1.10.2.js"></script
>
</head
>
<body
>
<div
class="inp_btn voice_btn active" id
="record">
按住 说话
</div
>
<script type
="text/javascript">
var recorder
;
var btnRecord
= $
('#record');
var startTime
= 0;
var recordTimer
= 300;
$
.ajax({
url
: 'url请求需要微信的一些东西 下面success就是返回的东西',
type
: 'get',
data
: { url
: url
},
success
: function
(data
) {
var json
= $
.parseJSON(data
);
wx
.config({
debug
: false,
appId
: json
.appid
,
timestamp
: json
.timestamp
,
nonceStr
: json
.nonceStr
,
signature
: json
.signature
,
jsApiList
: [
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"pauseVoice",
"stopVoice",
"onVoicePlayEnd",
"uploadVoice",
"downloadVoice",
]
});
wx
.ready(function
() {
btnRecord
.on('touchstart', function
(event) {
event.preventDefault();
startTime
= new Date().getTime();
recordTimer
= setTimeout(function
() {
wx
.startRecord({
success
: function
() {
localStorage
.rainAllowRecord
= 'true';
$
(".voice_icon").css("display", "block");
},
cancel
: function
() {
layer
.open({
content
: '用户拒绝了录音授权',
btn
: '确定',
shadeClose
: false,
});
}
});
}, 300);
}).on('touchend', function
(event) {
event.preventDefault();
if (new Date().getTime() - startTime
< 300) {
startTime
= 0;
clearTimeout(recordTimer
);
} else {
wx
.stopRecord({
success
: function
(res
) {
$
(".voice_icon").css("display", "none");
voice
.localId
= res
.localId
;
uploadVoice();
},
fail
: function
(res
) {
layer
.open({
content
: JSON
.stringify(res
),
btn
: '确定',
shadeClose
: false,
});
}
});
}
});
});
},
error
: function
() { }
})
function
uploadVoice() {
wx
.uploadVoice({
localId
: voice
.localId
,
isShowProgressTips
: 1,
success
: function
(res
) {
voice
.serverId
= res
.serverId
;
$
.ajax({
url
: '/WechatVoice/DownLoadVoice',
type
: 'post',
data
: { serverId
: res
.serverId
, Id
: Id
},
dataType
: "json",
success
: function
(data
) {
if (data
.Result
== true && data
.ResultCode
== 1) {
layer
.open({
content
: "录音上传完成!",
btn
: '确定',
shadeClose
: false,
yes
: function
(index
) {
window
.location
.href
= window
.location
.href
;
}
});
}
else {
layer
.open({
content
: data
.Message
,
btn
: '确定',
shadeClose
: false,
});
}
},
error
: function
(xhr
, errorType
, error
) {
layer
.open({
content
: error
,
btn
: '确定',
shadeClose
: false,
});
}
});
}
});
}
</script
>
</body
>
</html
>
WechatVoiceController.cs
using Loogn
.WeiXinSDK
;
using System
;
using System
.Collections
.Generic
;
using System
.IO
;
using System
.Linq
;
using System
.Web
;
using System
.Web
.Mvc
;
using WuDemo
.Common
;
namespace WuDemo
.Controllers
{
public class WechatVoiceController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult DownLoadVoice()
{
var file
= "";
try
{
var serverId
= Request
["serverId"];
file
= GetVoicePath(serverId
, CacheHelper
.GetAccessToken());
return Json(new ResultJson { Message
= file
, Result
= true, ResultCode
= 1 });
}
catch (Exception ex
)
{
return Json(new ResultJson { Message
= ex
.Message
, Result
= false, ResultCode
= 0 });
}
}
private string GetVoicePath(string voiceId
, string access_token
)
{
string voice
= "";
try
{
Log
.Debug("access_token:", access_token
);
DownloadFile downFile
= WeiXin
.DownloadMedia(voiceId
, access_token
);
if (downFile
.Stream
!= null)
{
string fileName
= Guid
.NewGuid().ToString();
string amrPath
= Server
.MapPath("~/upload/audior/");
if (!Directory
.Exists(amrPath
))
{
Directory
.CreateDirectory(amrPath
);
}
string amrFilename
= amrPath
+ fileName
+ ".amr";
using (FileStream fs
= new FileStream(amrFilename
, FileMode
.Create
))
{
byte[] datas
= new byte[downFile
.Stream
.Length
];
downFile
.Stream
.Read(datas
, 0, datas
.Length
);
fs
.Write(datas
, 0, datas
.Length
);
}
string mp3Path
= Server
.MapPath("~/upload/audio/");
if (!Directory
.Exists(mp3Path
))
{
Directory
.CreateDirectory(mp3Path
);
}
string mp3Filename
= mp3Path
+ fileName
+ ".mp3";
AudioHelper
.ConvertToMp3(Server
.MapPath("~/ffmpeg/"), amrFilename
, mp3Filename
);
voice
= fileName
;
Log
.Debug("voice:", voice
);
}
}
catch
{
}
return voice
;
}
}
}
AudioHelper.cs
using System
;
using System
.Collections
.Generic
;
using System
.Linq
;
using System
.Threading
;
using System
.Web
;
namespace WuDemo
.Common
{
public sealed class AudioHelper
{
private const string FfmpegUsername
= "ffmpeg";
private const string FfmpegPassword
= "it4pl803";
public static string ConvertToMp3(string ffmpegPath
, string soruceFilename
, string targetFileName
)
{
string cmd
= ffmpegPath
+ @"\ffmpeg.exe -i " + soruceFilename
+ " -ar 44100 -ab 128k " + targetFileName
;
return ConvertWithCmd(cmd
);
}
private static string ConvertWithCmd(string cmd
)
{
try
{
System.Diagnostics.Process process
= new System.Diagnostics.Process();
process
.StartInfo
.FileName
= "cmd.exe";
process
.StartInfo
.UseShellExecute
= false;
process
.StartInfo
.CreateNoWindow
= true;
process
.StartInfo
.RedirectStandardInput
= true;
process
.StartInfo
.RedirectStandardOutput
= true;
process
.StartInfo
.RedirectStandardError
= true;
process
.Start();
process
.StandardInput
.WriteLine(cmd
);
process
.StandardInput
.AutoFlush
= true;
Thread
.Sleep(1000);
process
.StandardInput
.WriteLine("exit");
process
.WaitForExit();
string outStr
= process
.StandardOutput
.ReadToEnd();
process
.Close();
return outStr
;
}
catch (Exception ex
)
{
return "error" + ex
.Message
;
}
}
}
}
文中需要 DownloadFile downFile = WeiXin.DownloadMedia(voiceId, access_token); 需要一个类库 到时候直接放到项目里面即可(我也是找到) http://files.cnblogs.com/files/hbh123/Loogn.WeiXinSDK.rar
转载请注明原文地址: https://www.6miu.com/read-36830.html