如何基于小程序實現(xiàn)發(fā)送語音消息及轉文字功能
更新時間:2022年11月15日 15:00:29 作者:摔跤貓子
最近為小程序增加語音識別轉文字的功能,坑路不斷,特此記錄,下面這篇文章主要給大家介紹了關于如何基于小程序實現(xiàn)發(fā)送語音消息及轉文字功能的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
此文主要在小程序內(nèi)聊天的基礎上實現(xiàn)語音發(fā)送及文字轉換。

小程序
賬號創(chuàng)建及工具準備
訪問微信公眾平臺,點擊賬號注冊。

選擇小程序,并在表單填寫所需的各項信息進行注冊。


在開發(fā)管理選擇開發(fā)設置,將AppID及AppSecret復制出來進行存儲。

下載安裝微信web開發(fā)者工具并創(chuàng)建一個新的項目,填入上圖所復制的AppId。


頁面大體設計
頁面上主要元素應該有語音發(fā)送按鈕、語音展示區(qū)域、語音轉換結果區(qū)域等,大致設計如下。

實現(xiàn)錄音功能
在小程序中獲取全局唯一的錄音管理器:RecorderManager wx.getRecorderManager()。
const recorderManager = wx.getRecorderManager()

先在頁面定義幾個按鈕,測試錄音管理器是否有效。

<button bindtap="start" class='btn'>開始錄音</button> <button bindtap="pause" class='btn'>暫停錄音</button> <button bindtap="resume" class='btn'>繼續(xù)錄音</button> <button bindtap="stop" class='btn'>停止錄音</button> <button bindtap="play" class='btn'>播放錄音</button>
在JS文件中實現(xiàn)開始錄音按鈕對應的事件,因為需要用到手機麥克風權限,所以需要先向用戶進行申請。

拼接插件API所需的各項參數(shù)。

const options = {
duration: 10000,//指定錄音的時長,單位 ms
sampleRate: 16000,//采樣率
numberOfChannels: 1,//錄音通道數(shù)
encodeBitRate: 96000,//編碼碼率
format: 'mp3',//音頻格式,有效值 aac/mp3
frameSize: 50,//指定幀大小,單位 KB
}
將錄音start的方法嵌入授權的方法中,并在錯誤回調進行提示。
//開始錄音
wx.authorize({
scope: 'scope.record',
success() {
console.log("錄音授權成功");
//第一次成功授權后 狀態(tài)切換為2
that.setData({
status: 2,
})
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//錯誤回調
recorderManager.onError((res) => {
console.log(res);
})
},
fail() {
console.log("第一次錄音授權失敗");
wx.showModal({
title: '提示',
content: '您未授權錄音,功能將無法使用',
showCancel: true,
confirmText: "授權",
confirmColor: "#52a2d8",
success: function (res) {
if (res.confirm) {
//確認則打開設置頁面(重點)
wx.openSetting({
success: (res) => {
console.log(res.authSetting);
if (!res.authSetting['scope.record']) {
//未設置錄音授權
console.log("未設置錄音授權");
wx.showModal({
title: '提示',
content: '您未授權錄音,功能將無法使用',
showCancel: false,
success: function (res) {
},
})
} else {
//第二次才成功授權
console.log("設置錄音授權成功");
that.setData({
status: 2,
})
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//錯誤回調
recorderManager.onError((res) => {
console.log(res);
})
}
},
fail: function () {
console.log("授權設置錄音失敗");
}
})
} else if (res.cancel) {
console.log("cancel");
}
},
fail: function () {
console.log("openfail");
}
})
}
})
點擊開始錄音,如果上述操作能夠正常完成,那么在小程序的頂部會有音量的標識閃爍同時控制臺也會有對應的結果輸出。

能夠正常的開始錄音功能后,繼續(xù)實現(xiàn)暫停錄音以及停止錄音功能,相比于獲取權限以及開始錄音相對簡單,只要針對全局錄音管理器做對應的操作即可。

//暫停錄音
pause: function () {
recorderManager.pause();
recorderManager.onPause((res) => {
console.log('暫停錄音')
})
},
//繼續(xù)錄音
resume: function () {
recorderManager.resume();
recorderManager.onStart(() => {
console.log('重新開始錄音')
});
//錯誤回調
recorderManager.onError((res) => {
console.log(res);
})
},
//停止錄音
stop: function () {
recorderManager.stop();
recorderManager.onStop((res) => {
this.tempFilePath = res.tempFilePath;
console.log('停止錄音', res.tempFilePath)
const { tempFilePath } = res
})
},
當點擊停止錄音時,將結果進行輸出并存儲,以便我們用來播放以及文字轉換;下圖中后綴為.mp3的就是我們所需要的錄音文件了。

實現(xiàn)播放音樂時需要創(chuàng)建另外一個對象:createInnerAudioContext。在JS定義之后,再實現(xiàn)界面上按鈕的事件,就能夠聽到自己美妙的聲音啦。



const innerAudioContext = wx.createInnerAudioContext()
//播放聲音
play: function () {
innerAudioContext.autoplay = true
innerAudioContext.src = this.tempFilePath,
innerAudioContext.onPlay(() => {
console.log('開始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
},
實現(xiàn)對話界面
基于小程序+C#實現(xiàn)聊天功能,增加語音樣式及語音轉換后的界面展示。
<view class="cu-chat">
<view class="cu-item self" >
<view class="main">
<view class="action text-bold text-grey">
3"
</view>
<view class="content shadow">
<text class="cuIcon-sound text-xxl padding-right-xl"> </text>
</view>
</view>
<view class="cu-avatar radius" style="background-image:url(userHead.jpg);"></view>
</view>
<view class="cu-item self" style="margin-top:-80rpx;">
<view class="main" >
<view class="content shadow" style="">
<text class="cuIcon-video text-xxl ">這里是語音轉換文字后的區(qū)域。</text>
</view>
</view>
<view class="date "> 2022-11-01 9:58</view>
<view class="cu-avatar radius" style="background-color: #F1F1F1;"></view>
</view>
在界面底部將錄音按鈕樣式進行調整,加上語音圖標,并增加對應的事件。

<view class="cu-bar foot input {{InputBottom!=0?'cur':''}}" style="bottom:{{InputBottom}}px">
<view class="action">
<text class="cuIcon-sound text-grey"></text>
</view>
<input class="solid-bottom" value="{{content}}" bindinput="formMsg" bindfocus="InputFocus" bindblur="InputBlur" adjust-position="{{false}}" focus="{{false}}" maxlength="300" cursor-spacing="10"></input>
<view class="action">
<text class="cuIcon-emojifill text-grey"></text>
</view>
<button class="cu-btn bg-green shadow" bindtap="sendMsg">發(fā)送</button>
</view>
.scrollPage {
height: 100vh;
}
.nav-list {
display: flex;
flex-wrap: wrap;
padding: 0px 40rpx 0px;
justify-content: space-between;
}
.nav-li {
padding: 30rpx;
border-radius: 12rpx;
width: 45%;
margin: 0 2.5% 40rpx;
background-image: url(https://image.weilanwl.com/color2.0/cardBg.png);
background-size: cover;
background-position: center;
position: relative;
z-index: 1;
}
.nav-li::after {
content: "";
position: absolute;
z-index: -1;
background-color: inherit;
width: 100%;
height: 100%;
left: 0;
bottom: -10%;
border-radius: 10rpx;
opacity: 0.2;
transform: scale(0.9, 0.9);
}
.nav-li.cur {
color: #fff;
background: rgb(94, 185, 94);
box-shadow: 4rpx 4rpx 6rpx rgba(94, 185, 94, 0.4);
}
.nav-title {
font-size: 32rpx;
font-weight: 300;
}
.nav-title::first-letter {
font-size: 40rpx;
margin-right: 4rpx;
}
.nav-name {
font-size: 28rpx;
text-transform: Capitalize;
margin-top: 20rpx;
position: relative;
}
.nav-name::before {
content: "";
position: absolute;
display: block;
width: 40rpx;
height: 6rpx;
background: #fff;
bottom: 0;
right: 0;
opacity: 0.5;
}
.nav-name::after {
content: "";
position: absolute;
display: block;
width: 100rpx;
height: 1px;
background: #fff;
bottom: 0;
right: 40rpx;
opacity: 0.3;
}
.nav-name::first-letter {
font-weight: bold;
font-size: 36rpx;
margin-right: 1px;
}
.nav-li text {
position: absolute;
right: 30rpx;
top: 30rpx;
font-size: 52rpx;
width: 60rpx;
height: 60rpx;
text-align: center;
line-height: 60rpx;
}
.text-light {
font-weight: 300;
}
可以增加一些細節(jié)處理,在錄音的時候增加計時,在結束的時候停止,將時長在界面上進行顯示。

語音轉換文字
賬號創(chuàng)建及應用申請
界面及錄音發(fā)送功能實現(xiàn)后,接下來需要申請語音轉換文字的API。以前公眾平臺是有一個插件可以進行轉換的,現(xiàn)在不知道什么原因下架了,所以只能使用替代方案。
訪問百度開放平臺選擇語音識別并領取免費資源


填寫表單所需的各項信息創(chuàng)建應用。

創(chuàng)建完畢后回到應用列表,將API Key 以及Serect Key復制出來,后面我們需要通過這些憑證來獲取Token。


實現(xiàn)語音轉文字
回到小程序,在JS文件中的onLoad函數(shù)中請求獲取Token的接口,這時候就需要用到我們剛才所申請的ApiKey等信息了。


/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
let that = this;
let ApiKey='這里填你所申請的ApiKey';
let SecretKey='這里填你所申請的SecretKey';
wx.request({
url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ApiKey+'&client_secret='+SecretKey,
method: 'POST',
success: function (res) {
that.setData({
AccessToken:res.data.access_token
});
}
});
},
編譯程序,檢查接口是否有正常返回,下圖所標記的字段就是我們所需要的token了,它的有效期為30天,記得要定期且及時更新。

拼接參數(shù)并調用接口,我們這里先使用JSON的方式上傳,因為小程序內(nèi)轉換raw有些麻煩;如果請求失敗,可以先看一下本地設置中是否開啟不校驗合法域名。


let data = {
"format":"pcm",
"rate":16000,
"dev_pid":1537,
"channel":1,
"token":xxx,
"cuid":"baidu_workshop",
"len":4096,
"speech":'這里放你存放的mp3文件且轉換為base格式', // xxx為 base64(FILE_CONTENT)
};
wx.request({
url: 'http://vop.baidu.com/server_api',
method: 'post',
Content-Type:'application/json',
success: function (res) {
console.log(res);
}
});
將接口返回的數(shù)據(jù)進行打印輸出,result字段就是語音轉換后的結果了。
{"corpus_no":"6433214037620997779","err_msg":"success.","err_no":0,"result":["沸羊羊我討厭你,"],"sn":"371191073711497849365"}在wxml界面語音框增加事件,綁定上述語音轉文字的方法,將轉換結果進行顯示;最終結果如下圖,大家測試的時候盡量用普通話,這樣結果會相對來說準確一些。

總結
到此這篇關于如何基于小程序實現(xiàn)發(fā)送語音消息及轉文字功能的文章就介紹到這了,更多相關小程序發(fā)送語音消息及轉文字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
javascript中的replace函數(shù)(帶注釋demo)
在js中有兩個replace函數(shù) 一個是location.replace(url) 跳轉到一個新的url.一個string.replace("xx","yy") 替換字符串 返回一個新的字符串,該方法并不改變字符串本身。下面通過本文給大家介紹javascript中的replace函數(shù)2018-01-01
javascript獲取select的當前值示例代碼(兼容IE/Firefox/Opera/Chrome)
本篇文章主要介紹了javascript獲取select的當前值示例代碼(兼容IE/Firefox/Opera/Chrome) 需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12
適用于javascript開發(fā)者的Processing.js入門教程
這篇文章主要介紹了適用于javascript開發(fā)者的Processing.js入門教程,感興趣的小伙伴們可以參考一下2016-02-02

