如何基于小程序?qū)崿F(xiàn)發(fā)送語(yǔ)音消息及轉(zhuǎn)文字功能
此文主要在小程序內(nèi)聊天的基礎(chǔ)上實(shí)現(xiàn)語(yǔ)音發(fā)送及文字轉(zhuǎn)換。
小程序
賬號(hào)創(chuàng)建及工具準(zhǔn)備
訪問(wèn)微信公眾平臺(tái),點(diǎn)擊賬號(hào)注冊(cè)。
選擇小程序,并在表單填寫所需的各項(xiàng)信息進(jìn)行注冊(cè)。
在開發(fā)管理選擇開發(fā)設(shè)置,將AppID及AppSecret復(fù)制出來(lái)進(jìn)行存儲(chǔ)。
下載安裝微信web開發(fā)者工具并創(chuàng)建一個(gè)新的項(xiàng)目,填入上圖所復(fù)制的AppId。
頁(yè)面大體設(shè)計(jì)
頁(yè)面上主要元素應(yīng)該有語(yǔ)音發(fā)送按鈕、語(yǔ)音展示區(qū)域、語(yǔ)音轉(zhuǎn)換結(jié)果區(qū)域等,大致設(shè)計(jì)如下。
實(shí)現(xiàn)錄音功能
在小程序中獲取全局唯一的錄音管理器:RecorderManager wx.getRecorderManager()。
const recorderManager = wx.getRecorderManager()
先在頁(yè)面定義幾個(gè)按鈕,測(cè)試錄音管理器是否有效。
<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文件中實(shí)現(xiàn)開始錄音按鈕對(duì)應(yīng)的事件,因?yàn)樾枰玫绞謾C(jī)麥克風(fēng)權(quán)限,所以需要先向用戶進(jìn)行申請(qǐng)。
拼接插件API所需的各項(xiàng)參數(shù)。
const options = { duration: 10000,//指定錄音的時(shí)長(zhǎng),單位 ms sampleRate: 16000,//采樣率 numberOfChannels: 1,//錄音通道數(shù) encodeBitRate: 96000,//編碼碼率 format: 'mp3',//音頻格式,有效值 aac/mp3 frameSize: 50,//指定幀大小,單位 KB }
將錄音start的方法嵌入授權(quán)的方法中,并在錯(cuò)誤回調(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') }); //錯(cuò)誤回調(diào) recorderManager.onError((res) => { console.log(res); }) }, fail() { console.log("第一次錄音授權(quán)失敗"); wx.showModal({ title: '提示', content: '您未授權(quán)錄音,功能將無(wú)法使用', showCancel: true, confirmText: "授權(quán)", confirmColor: "#52a2d8", success: function (res) { if (res.confirm) { //確認(rèn)則打開設(shè)置頁(yè)面(重點(diǎn)) 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)錄音,功能將無(wú)法使用', 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') }); //錯(cuò)誤回調(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"); } }) } })
點(diǎn)擊開始錄音,如果上述操作能夠正常完成,那么在小程序的頂部會(huì)有音量的標(biāo)識(shí)閃爍同時(shí)控制臺(tái)也會(huì)有對(duì)應(yīng)的結(jié)果輸出。
能夠正常的開始錄音功能后,繼續(xù)實(shí)現(xiàn)暫停錄音以及停止錄音功能,相比于獲取權(quán)限以及開始錄音相對(duì)簡(jiǎn)單,只要針對(duì)全局錄音管理器做對(duì)應(yīng)的操作即可。
//暫停錄音 pause: function () { recorderManager.pause(); recorderManager.onPause((res) => { console.log('暫停錄音') }) }, //繼續(xù)錄音 resume: function () { recorderManager.resume(); recorderManager.onStart(() => { console.log('重新開始錄音') }); //錯(cuò)誤回調(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)點(diǎn)擊停止錄音時(shí),將結(jié)果進(jìn)行輸出并存儲(chǔ),以便我們用來(lái)播放以及文字轉(zhuǎn)換;下圖中后綴為.mp3的就是我們所需要的錄音文件了。
實(shí)現(xiàn)播放音樂(lè)時(shí)需要?jiǎng)?chuàng)建另外一個(gè)對(duì)象:createInnerAudioContext。在JS定義之后,再實(shí)現(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) }) },
實(shí)現(xiàn)對(duì)話界面
基于小程序+C#實(shí)現(xiàn)聊天功能,增加語(yǔ)音樣式及語(yǔ)音轉(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 ">這里是語(yǔ)音轉(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)整,加上語(yǔ)音圖標(biāo),并增加對(duì)應(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é)處理,在錄音的時(shí)候增加計(jì)時(shí),在結(jié)束的時(shí)候停止,將時(shí)長(zhǎng)在界面上進(jìn)行顯示。
語(yǔ)音轉(zhuǎn)換文字
賬號(hào)創(chuàng)建及應(yīng)用申請(qǐng)
界面及錄音發(fā)送功能實(shí)現(xiàn)后,接下來(lái)需要申請(qǐng)語(yǔ)音轉(zhuǎn)換文字的API。以前公眾平臺(tái)是有一個(gè)插件可以進(jìn)行轉(zhuǎn)換的,現(xiàn)在不知道什么原因下架了,所以只能使用替代方案。
訪問(wèn)百度開放平臺(tái)選擇語(yǔ)音識(shí)別并領(lǐng)取免費(fèi)資源
填寫表單所需的各項(xiàng)信息創(chuàng)建應(yīng)用。
創(chuàng)建完畢后回到應(yīng)用列表,將API Key 以及Serect Key復(fù)制出來(lái),后面我們需要通過(guò)這些憑證來(lái)獲取Token。
實(shí)現(xiàn)語(yǔ)音轉(zhuǎn)文字
回到小程序,在JS文件中的onLoad函數(shù)中請(qǐng)求獲取Token的接口,這時(shí)候就需要用到我們剛才所申請(qǐng)的ApiKey等信息了。
/** * 生命周期函數(shù)--監(jiān)聽頁(yè)面加載 */ onLoad(options) { let that = this; let ApiKey='這里填你所申請(qǐng)的ApiKey'; let SecretKey='這里填你所申請(qǐng)的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í)更新。
拼接參數(shù)并調(diào)用接口,我們這里先使用JSON的方式上傳,因?yàn)樾〕绦騼?nèi)轉(zhuǎn)換raw有些麻煩;如果請(qǐng)求失敗,可以先看一下本地設(shè)置中是否開啟不校驗(yàn)合法域名。
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字段就是語(yǔ)音轉(zhuǎn)換后的結(jié)果了。
{"corpus_no":"6433214037620997779","err_msg":"success.","err_no":0,"result":["沸羊羊我討厭你,"],"sn":"371191073711497849365"}
在wxml界面語(yǔ)音框增加事件,綁定上述語(yǔ)音轉(zhuǎn)文字的方法,將轉(zhuǎn)換結(jié)果進(jìn)行顯示;最終結(jié)果如下圖,大家測(cè)試的時(shí)候盡量用普通話,這樣結(jié)果會(huì)相對(duì)來(lái)說(shuō)準(zhǔn)確一些。
總結(jié)
到此這篇關(guān)于如何基于小程序?qū)崿F(xiàn)發(fā)送語(yǔ)音消息及轉(zhuǎn)文字功能的文章就介紹到這了,更多相關(guān)小程序發(fā)送語(yǔ)音消息及轉(zhuǎn)文字內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript中的replace函數(shù)(帶注釋demo)
在js中有兩個(gè)replace函數(shù) 一個(gè)是location.replace(url) 跳轉(zhuǎn)到一個(gè)新的url.一個(gè)string.replace("xx","yy") 替換字符串 返回一個(gè)新的字符串,該方法并不改變字符串本身。下面通過(guò)本文給大家介紹javascript中的replace函數(shù)2018-01-01javascript獲取select的當(dāng)前值示例代碼(兼容IE/Firefox/Opera/Chrome)
本篇文章主要介紹了javascript獲取select的當(dāng)前值示例代碼(兼容IE/Firefox/Opera/Chrome) 需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2013-12-12如何判斷Javascript對(duì)象是否存在的簡(jiǎn)單實(shí)例
下面小編就為大家?guī)?lái)一篇如何判斷Javascript對(duì)象是否存在的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-05-05基于js實(shí)現(xiàn)逐步顯示文字輸出代碼實(shí)例
這篇文章主要介紹了基于js實(shí)現(xiàn)逐步顯示文字輸出代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04適用于javascript開發(fā)者的Processing.js入門教程
這篇文章主要介紹了適用于javascript開發(fā)者的Processing.js入門教程,感興趣的小伙伴們可以參考一下2016-02-02讓iframe框架網(wǎng)頁(yè)在任何瀏覽器下自動(dòng)伸縮
很多朋友都在使用iframe中遇到過(guò)不能自動(dòng)隨頁(yè)面伸縮,特別是動(dòng)態(tài)讀取頁(yè)面的時(shí)候,會(huì)出現(xiàn)滾動(dòng)條,影響美觀,今天研究一下了,發(fā)現(xiàn)了一個(gè)簡(jiǎn)單解決的辦法,可以在IE,F(xiàn)IREFOX,OPERA下使用2006-08-08JavaScript中forEach和map詳細(xì)講解
foreach和map都是JavaScript中數(shù)組的常用方法,它們都可以對(duì)數(shù)組中的每個(gè)元素執(zhí)行一個(gè)函數(shù),但是它們有一些區(qū)別,下面這篇文章主要給大家介紹了關(guān)于JavaScript中forEach和map詳細(xì)講解的相關(guān)資料,需要的朋友可以參考下2023-11-11