如何基于小程序?qū)崿F(xiàn)發(fā)送語音消息及轉(zhuǎn)文字功能
此文主要在小程序內(nèi)聊天的基礎(chǔ)上實現(xiàn)語音發(fā)送及文字轉(zhuǎn)換。
小程序
賬號創(chuàng)建及工具準(zhǔn)備
訪問微信公眾平臺,點擊賬號注冊。
選擇小程序,并在表單填寫所需的各項信息進(jìn)行注冊。
在開發(fā)管理選擇開發(fā)設(shè)置,將AppID及AppSecret復(fù)制出來進(jìn)行存儲。
下載安裝微信web開發(fā)者工具并創(chuàng)建一個新的項目,填入上圖所復(fù)制的AppId。
頁面大體設(shè)計
頁面上主要元素應(yīng)該有語音發(fā)送按鈕、語音展示區(qū)域、語音轉(zhuǎn)換結(jié)果區(qū)域等,大致設(shè)計如下。
實現(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)開始錄音按鈕對應(yīng)的事件,因為需要用到手機(jī)麥克風(fēng)權(quán)限,所以需要先向用戶進(jìn)行申請。
拼接插件API所需的各項參數(shù)。
const options = { duration: 10000,//指定錄音的時長,單位 ms sampleRate: 16000,//采樣率 numberOfChannels: 1,//錄音通道數(shù) encodeBitRate: 96000,//編碼碼率 format: 'mp3',//音頻格式,有效值 aac/mp3 frameSize: 50,//指定幀大小,單位 KB }
將錄音start的方法嵌入授權(quán)的方法中,并在錯誤回調(diào)進(jìn)行提示。
//開始錄音 wx.authorize({ scope: 'scope.record', success() { console.log("錄音授權(quán)成功"); //第一次成功授權(quán)后 狀態(tài)切換為2 that.setData({ status: 2, }) recorderManager.start(options); recorderManager.onStart(() => { console.log('recorder start') }); //錯誤回調(diào) recorderManager.onError((res) => { console.log(res); }) }, fail() { console.log("第一次錄音授權(quán)失敗"); wx.showModal({ title: '提示', content: '您未授權(quán)錄音,功能將無法使用', showCancel: true, confirmText: "授權(quán)", confirmColor: "#52a2d8", success: function (res) { if (res.confirm) { //確認(rèn)則打開設(shè)置頁面(重點) wx.openSetting({ success: (res) => { console.log(res.authSetting); if (!res.authSetting['scope.record']) { //未設(shè)置錄音授權(quán) console.log("未設(shè)置錄音授權(quán)"); wx.showModal({ title: '提示', content: '您未授權(quán)錄音,功能將無法使用', showCancel: false, success: function (res) { }, }) } else { //第二次才成功授權(quán) console.log("設(shè)置錄音授權(quán)成功"); that.setData({ status: 2, }) recorderManager.start(options); recorderManager.onStart(() => { console.log('recorder start') }); //錯誤回調(diào) recorderManager.onError((res) => { console.log(res); }) } }, fail: function () { console.log("授權(quán)設(shè)置錄音失敗"); } }) } else if (res.cancel) { console.log("cancel"); } }, fail: function () { console.log("openfail"); } }) } })
點擊開始錄音,如果上述操作能夠正常完成,那么在小程序的頂部會有音量的標(biāo)識閃爍同時控制臺也會有對應(yīng)的結(jié)果輸出。
能夠正常的開始錄音功能后,繼續(xù)實現(xiàn)暫停錄音以及停止錄音功能,相比于獲取權(quán)限以及開始錄音相對簡單,只要針對全局錄音管理器做對應(yīng)的操作即可。
//暫停錄音 pause: function () { recorderManager.pause(); recorderManager.onPause((res) => { console.log('暫停錄音') }) }, //繼續(xù)錄音 resume: function () { recorderManager.resume(); recorderManager.onStart(() => { console.log('重新開始錄音') }); //錯誤回調(diào) recorderManager.onError((res) => { console.log(res); }) }, //停止錄音 stop: function () { recorderManager.stop(); recorderManager.onStop((res) => { this.tempFilePath = res.tempFilePath; console.log('停止錄音', res.tempFilePath) const { tempFilePath } = res }) },
當(dāng)點擊停止錄音時,將結(jié)果進(jìn)行輸出并存儲,以便我們用來播放以及文字轉(zhuǎn)換;下圖中后綴為.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)聊天功能,增加語音樣式及語音轉(zhuǎ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 ">這里是語音轉(zhuǎn)換文字后的區(qū)域。</text> </view> </view> <view class="date "> 2022-11-01 9:58</view> <view class="cu-avatar radius" style="background-color: #F1F1F1;"></view> </view>
在界面底部將錄音按鈕樣式進(jìn)行調(diào)整,加上語音圖標(biāo),并增加對應(yīng)的事件。
<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; }
可以增加一些細(xì)節(jié)處理,在錄音的時候增加計時,在結(jié)束的時候停止,將時長在界面上進(jìn)行顯示。
語音轉(zhuǎn)換文字
賬號創(chuàng)建及應(yīng)用申請
界面及錄音發(fā)送功能實現(xiàn)后,接下來需要申請語音轉(zhuǎn)換文字的API。以前公眾平臺是有一個插件可以進(jìn)行轉(zhuǎn)換的,現(xiàn)在不知道什么原因下架了,所以只能使用替代方案。
訪問百度開放平臺選擇語音識別并領(lǐng)取免費資源
填寫表單所需的各項信息創(chuàng)建應(yīng)用。
創(chuàng)建完畢后回到應(yīng)用列表,將API Key 以及Serect Key復(fù)制出來,后面我們需要通過這些憑證來獲取Token。
實現(xiàn)語音轉(zhuǎ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 }); } }); },
編譯程序,檢查接口是否有正常返回,下圖所標(biāo)記的字段就是我們所需要的token了,它的有效期為30天,記得要定期且及時更新。
拼接參數(shù)并調(diào)用接口,我們這里先使用JSON的方式上傳,因為小程序內(nèi)轉(zhuǎn)換raw有些麻煩;如果請求失敗,可以先看一下本地設(shè)置中是否開啟不校驗合法域名。
let data = { "format":"pcm", "rate":16000, "dev_pid":1537, "channel":1, "token":xxx, "cuid":"baidu_workshop", "len":4096, "speech":'這里放你存放的mp3文件且轉(zhuǎn)換為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ù)進(jìn)行打印輸出,result字段就是語音轉(zhuǎn)換后的結(jié)果了。
{"corpus_no":"6433214037620997779","err_msg":"success.","err_no":0,"result":["沸羊羊我討厭你,"],"sn":"371191073711497849365"}
在wxml界面語音框增加事件,綁定上述語音轉(zhuǎn)文字的方法,將轉(zhuǎn)換結(jié)果進(jìn)行顯示;最終結(jié)果如下圖,大家測試的時候盡量用普通話,這樣結(jié)果會相對來說準(zhǔn)確一些。
總結(jié)
到此這篇關(guān)于如何基于小程序?qū)崿F(xiàn)發(fā)送語音消息及轉(zhuǎn)文字功能的文章就介紹到這了,更多相關(guān)小程序發(fā)送語音消息及轉(zhuǎn)文字內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript中的replace函數(shù)(帶注釋demo)
在js中有兩個replace函數(shù) 一個是location.replace(url) 跳轉(zhuǎn)到一個新的url.一個string.replace("xx","yy") 替換字符串 返回一個新的字符串,該方法并不改變字符串本身。下面通過本文給大家介紹javascript中的replace函數(shù)2018-01-01javascript獲取select的當(dāng)前值示例代碼(兼容IE/Firefox/Opera/Chrome)
本篇文章主要介紹了javascript獲取select的當(dāng)前值示例代碼(兼容IE/Firefox/Opera/Chrome) 需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12適用于javascript開發(fā)者的Processing.js入門教程
這篇文章主要介紹了適用于javascript開發(fā)者的Processing.js入門教程,感興趣的小伙伴們可以參考一下2016-02-02JavaScript中forEach和map詳細(xì)講解
foreach和map都是JavaScript中數(shù)組的常用方法,它們都可以對數(shù)組中的每個元素執(zhí)行一個函數(shù),但是它們有一些區(qū)別,下面這篇文章主要給大家介紹了關(guān)于JavaScript中forEach和map詳細(xì)講解的相關(guān)資料,需要的朋友可以參考下2023-11-11