위 챗 음성 업로드 다운로드 기능 인 스 턴 스 코드
<div class="inp_btn voice_btn active" id="record">
</div>
다음은 위 챗 jssdk 를 호출 하 는 방법 입 니 다.
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);
//alert(json);
// jssdk。【 AMD/CMD 】
wx.config({
debug: false, // , api alert , , pc , log , pc 。
appId: json.appid, // ,
timestamp: json.timestamp, // ,
nonceStr: json.nonceStr, // ,
signature: json.signature, // , , 1
jsApiList: [
"startRecord",
"stopRecord",
"onVoiceRecordEnd",
"playVoice",
"pauseVoice",
"stopVoice",
"onVoicePlayEnd",
"uploadVoice",
"downloadVoice",
] // , JS , JS 2
});
wx.ready(function () {
btnRecord.on('touchstart', function (event) {
event.preventDefault();
startTime = new Date().getTime();
// ,
recordTimer = setTimeout(function () {
wx.startRecord({
success: function () {
localStorage.rainAllowRecord = 'true';
//style="display:block"
$(".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) {
//alert(JSON.stringify(res));
layer.open({
content: JSON.stringify(res),
btn: ' ',
shadeClose: false,
});
}
});
}
});
});
},
error: function () { }
})
음성 업로드 방법
function uploadVoice() {
//
// , 3 , ,
wx.uploadVoice({
localId: voice.localId, // ID, stopRecord
isShowProgressTips: 1, // 1,
success: function (res) {
// alert(JSON.stringify(res));
// id(res.serverId) 。
voice.serverId = res.serverId;
$.ajax({
url: '/QyhSpeech/DownLoadVoice',
type: 'post',
data: { serverId: res.serverId, Id: Id },
dataType: "json",
success: function (data) {
if (data.Result == true && data.ResultCode == 1) {
layer.open({
content: " !",//data.Message
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,
});
}
});
}
});
}
백 스테이지 호출 방법 ffmpeg.exe 자체 다운로드 가 필요 합 니 다.
//
private string GetVoicePath(string voiceId, string access_token)
{
string voice = "";
try
{
Log.Debug("access_token:", access_token);
// downloadmedia downfile
DownloadFile downFile = WeiXin.DownloadMedia(voiceId, access_token);
if (downFile.Stream != null)
{
string fileName = Guid.NewGuid().ToString();
// amr
string amrPath = Server.MapPath("~/upload/audior/");
if (!Directory.Exists(amrPath))
{
Directory.CreateDirectory(amrPath);
}
string amrFilename = amrPath + fileName + ".amr";
//var ss = GetAMRFileDuration(amrFilename);
//Log.Debug("ss", ss.ToString());
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);
}
// mp3
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;
}
GetVoicePath 호출
//
public JsonResult DownLoadVoice()
{
var file = "";
try
{
var serverId = Request["serverId"];// 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 });
}
}
AudioHelper 클래스
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace EYO.Common
{
/// <summary>
///
/// </summary>
public sealed class AudioHelper
{
private const string FfmpegUsername = "ffmpeg";
private const string FfmpegPassword = "it4pl803";
/// <summary>
///
/// </summary>
/// <param name="ffmpegPath">ffmpeg </param>
/// <param name="soruceFilename"> </param>
/// <param name="targetFileName"> </param>
/// <returns></returns>
public static string ConvertToMp3(string ffmpegPath, string soruceFilename, string targetFileName)
{
//string cmd = ffmpegPath + @"\ffmpeg.exe -i " + soruceFilename + " " + 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;
}
}
}
}
글 에 빨간색 을 표시 하려 면 다음 과 같은 라 이브 러 리 를 글 의 마지막 링크 에 넣 어야 합 니 다.그때 프로젝트 에 직접 넣 으 면 됩 니 다.(저도 찾 았 습 니 다)총결산
위 에서 말 한 것 은 소 편 이 여러분 에 게 소개 한 위 챗 음성 업로드 다운로드 기능 인 스 턴 스 코드 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 저 에 게 메 시 지 를 남 겨 주세요.소 편 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Node.js를 사용하여 Chatwork에 이미지 업로드ChatworkAPI로 이미지를 업로드하고 싶을 때 curl을 사용하면 바삭바삭할 수 있습니다만, Node.js로 사용하고 싶은 경우의 경우도 있다고 생각합니다. 다만, 검색해 보면 Python과 ChatworkAP...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.