index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import {
  2. getreadInfo
  3. } from '~/api/video'
  4. import {
  5. publishWorks,
  6. uploadPk
  7. } from '~/api/works'
  8. import {
  9. createStoreBindings
  10. } from 'mobx-miniprogram-bindings'
  11. import {
  12. store
  13. } from '~/store/index'
  14. const aiengine = require('~/utils/ChivoxAiEngine')
  15. const sha1 = require('~/utils/sha1');
  16. // 文章行高
  17. let rowH = 0
  18. let videoContext = null
  19. // 滚动变色定时器
  20. let stl = null
  21. // 倒计时
  22. let setTimeoutObj = null
  23. // 录音
  24. let innerAudioContext = null
  25. let resultAudioContext = null
  26. /*创建基础引擎*/
  27. let wsEngine = aiengine.createWsEngine({});
  28. /*微信录音*/
  29. let recorderManager = wx.getRecorderManager();
  30. Page({
  31. data: {
  32. videoInfo: {},
  33. currentRow: null,
  34. state: false,
  35. countDown: {
  36. state: false,
  37. num: 3,
  38. },
  39. contentH: 0,
  40. scrollTop: 0,
  41. //如果readingReset为true就是重读
  42. readingReset: false,
  43. //readingType为public是普通阅读,为pk是pk逻辑
  44. readingType: 'public',
  45. percent: 0,
  46. uploadState: false,
  47. article: [{
  48. id: 1,
  49. text: '传说在很久很久以前,',
  50. time: '0'
  51. }, {
  52. id: 2,
  53. text: '天和地还没有分开,',
  54. time: '4010'
  55. }, {
  56. id: 3,
  57. text: '整个宇宙混沌一团,',
  58. time: '7080'
  59. }, {
  60. id: 4,
  61. text: '像个大鸡蛋。',
  62. time: '10150'
  63. }, {
  64. id: 5,
  65. text: '有个叫盘古的大神,',
  66. time: '13150'
  67. }, {
  68. id: 6,
  69. text: '昏睡了一万八千年。',
  70. time: '16190'
  71. }, {
  72. id: 7,
  73. text: '一天,大神醒来,睁眼一看,',
  74. time: '20030'
  75. }, {
  76. id: 8,
  77. text: '周围黑乎乎一片,',
  78. time: '24210'
  79. }, {
  80. id: 9,
  81. text: '什么也看不见。',
  82. time: '27300'
  83. }]
  84. },
  85. onLoad(options) {
  86. let videoId = options.videoId
  87. this.getreadInfo(videoId)
  88. let data = this.data.article
  89. data = data.map((item, index) => {
  90. item.readTime = data[index + 1] ? data[index + 1].time - item.time : ''
  91. return item
  92. })
  93. this.setData({
  94. article: data,
  95. readingReset: options.reset || false,
  96. readingType: options.readingType || 'public'
  97. })
  98. // 手工绑定
  99. this.storeBindings = createStoreBindings(this, {
  100. store,
  101. fields: {
  102. userInfo: 'userInfo',
  103. readDetail: 'readDetail',
  104. pkData: 'pkData'
  105. },
  106. actions: {
  107. setReadDetail: 'setReadDetail'
  108. }
  109. })
  110. if (!options.reset) {
  111. this.getHeight()
  112. }
  113. // 录音授权
  114. wx.getSetting({
  115. success(res) {
  116. if (!res.authSetting['scope.record']) {
  117. wx.authorize({
  118. scope: 'scope.record',
  119. success() {
  120. // 用户已经同意小程序使用录音功能,后续调用接口不会弹窗询问
  121. wx.getRecorderManager()
  122. }
  123. })
  124. }
  125. }
  126. })
  127. /*监听评测结果:必须在基础引擎创建后,调用任何评测接口前设置监听,否则有可能收不到相关事件。*/
  128. wsEngine.onResult((res) => {
  129. this.getRecordScore(res)
  130. });
  131. wsEngine.onErrorResult((res) => {
  132. console.log("===收到错误结果=============", res)
  133. });
  134. },
  135. // 获取阅读内容
  136. async getreadInfo(videoId) {
  137. let videoInfo = await getreadInfo(videoId)
  138. wx.setNavigationBarTitle({
  139. title: videoInfo.userRead.title
  140. })
  141. this.setData({
  142. videoInfo
  143. })
  144. if (!this.data.videoInfo.userReadExtend) {
  145. this.videoContext = wx.createVideoContext('myVideo')
  146. } else {
  147. this.innerAudioContext = wx.createInnerAudioContext();
  148. this.innerAudioContext.src = videoInfo.userRead.audioPath
  149. this.innerAudioContext.onEnded(res => {
  150. this.finishRecord()
  151. })
  152. this.innerAudioContext.onStop((res) => {
  153. this.finishRecord()
  154. });
  155. }
  156. },
  157. // 开始录制
  158. setCountDown() {
  159. if (this.data.state) {
  160. this.finishRecord()
  161. return
  162. }
  163. if (this.data.readingReset) {
  164. this.clearReset()
  165. this.getHeight()
  166. }
  167. this.setData({
  168. 'countDown.state': true
  169. })
  170. this.stl = setInterval(() => {
  171. if (this.data.countDown.num == 0) {
  172. clearInterval(this.stl)
  173. this.setData({
  174. state: true,
  175. countDown: {
  176. state: false,
  177. num: 3
  178. }
  179. })
  180. this.soundRecording()
  181. this.playMediaState()
  182. this.startRecording()
  183. } else {
  184. this.setData({
  185. 'countDown.num': --this.data.countDown.num
  186. })
  187. }
  188. }, 1000)
  189. },
  190. // 录音
  191. soundRecording() {
  192. /*调用微信开始录音接口,并启动语音评测*/
  193. let timeStamp = new Date().getTime()
  194. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  195. let app = {
  196. applicationId: '16075689600000da',
  197. sig, //签名字符串
  198. alg: 'sha1',
  199. timestamp: timeStamp + '',
  200. userId: wx.getStorageSync('uid')
  201. }
  202. let lessonText = this.data.videoInfo.userRead.lessonText;
  203. wsEngine.start({
  204. request: {
  205. coreType: "cn.pred.raw",
  206. refText: lessonText,
  207. rank: 100,
  208. attachAudioUrl: 1,
  209. result: {
  210. details: {
  211. gop_adjust: 1
  212. }
  213. }
  214. },
  215. app,
  216. audio: {
  217. audioType: "mp3",
  218. channel: 1,
  219. sampleBytes: 2,
  220. sampleRate: 16000
  221. },
  222. success: (res) => {
  223. /*引擎启动成功,可以启动录音机开始录音,并将音频片传给引擎*/
  224. const options = {
  225. sampleRate: 44100, //采样率
  226. numberOfChannels: 1, //录音通道数
  227. encodeBitRate: 192000, //编码码率
  228. format: 'mp3', //音频格式,有效值aac/mp3
  229. frameSize: 50 //指定帧大小,单位 KB
  230. };
  231. //开始录音,在开始录音回调中feed音频片
  232. recorderManager.start(options);
  233. },
  234. fail: (res) => {
  235. console.log("fail============= " + res);
  236. },
  237. });
  238. //监听录音开始事件
  239. recorderManager.onStart(() => {});
  240. //监听录音结束事件
  241. recorderManager.onStop((res) => {
  242. console.log('录音结束', res);
  243. this.setData({
  244. tempFilePath: res.tempFilePath,
  245. });
  246. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  247. wsEngine.stop({
  248. success: () => {
  249. console.log('====== wsEngine stop success ======');
  250. },
  251. fail: (res) => {
  252. console.log('录音结束报错', res);
  253. },
  254. });
  255. });
  256. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  257. recorderManager.onFrameRecorded((res) => {
  258. const {
  259. frameBuffer
  260. } = res
  261. //TODO 调用feed接口传递音频片给驰声评测引擎
  262. wsEngine.feed({
  263. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  264. success: () => {
  265. console.log('feed success.监听已录制完指定帧大小的文件事件')
  266. },
  267. fail: (res) => {
  268. console.log('监听已录制完指定帧大小报错', res)
  269. },
  270. });
  271. });
  272. },
  273. // 结束录制
  274. finishRecord() {
  275. recorderManager.stop();
  276. this.stopMediaState()
  277. clearTimeout(this.setTimeoutObj)
  278. clearInterval(this.stl)
  279. this.setData({
  280. state: false,
  281. currentRow: null,
  282. scrollTop: 0
  283. })
  284. },
  285. // 测试的
  286. pkResult() {
  287. wx.redirectTo({
  288. url: `/pages/pkResult/index`,
  289. })
  290. },
  291. // 字体换行
  292. startRecording() {
  293. if (this.data.currentRow == null) {
  294. this.setData({
  295. currentRow: 0
  296. })
  297. }
  298. let row = this.data.article[this.data.currentRow]
  299. if (!row.readTime) {
  300. return
  301. }
  302. this.setTimeoutObj = setTimeout(() => {
  303. this.setData({
  304. currentRow: ++this.data.currentRow
  305. })
  306. this.setData({
  307. scrollTop: this.rowH * this.data.currentRow
  308. })
  309. this.startRecording()
  310. },
  311. row.readTime);
  312. },
  313. // 视频播放结束
  314. videoEnd() {
  315. this.finishRecord()
  316. },
  317. // 获取测评结果
  318. getRecordScore(res) {
  319. console.log('获取评测结果');
  320. const result = res.result;
  321. const integrity = Math.floor(result.integrity); //完成度
  322. const tone = Math.floor(result.tone); // 语调声调
  323. const accuracy = Math.floor(result.overall); // 准确度 发音分
  324. const fluency = Math.floor(result.fluency.overall); //流利度
  325. let myOverall = Math.floor(integrity * 0.3 + accuracy * 0.5 + fluency * 0.1 + tone * 0.1);
  326. let detail = {
  327. integrity,
  328. tone,
  329. accuracy,
  330. fluency,
  331. myOverall,
  332. tempFilePath: this.data.tempFilePath,
  333. title: this.data.videoInfo.userRead.title,
  334. id: this.data.videoInfo.userRead.exampleId,
  335. }
  336. this.setReadDetail(detail)
  337. console.log(this.data.readingType, 'readingType');
  338. if (this.data.readingType == 'public') {
  339. wx.redirectTo({
  340. url: '/pages/score/index'
  341. })
  342. } else {
  343. this.uploadAudio(detail)
  344. }
  345. },
  346. // 挑战录音上传
  347. uploadAudio(detail) {
  348. this.setData({
  349. uploadState: true
  350. })
  351. const uploadTask = wx.uploadFile({
  352. url: 'https://reader-api.ai160.com//file/upload',
  353. filePath: this.data.tempFilePath,
  354. name: '朗读录音',
  355. header: {
  356. uid: wx.getStorageSync('uid')
  357. },
  358. success: async (res) => {
  359. const formateRes = JSON.parse(res.data);
  360. let audioPath = formateRes.data;
  361. let uploadRes = await publishWorks({
  362. exampleId: this.data.pkData.exampleId,
  363. audioPath
  364. })
  365. console.log('uploadRes', uploadRes);
  366. /* let winnerUId = this.data.pkData > detail.myOverall ? this.data.pkData.exampleId : this.data.pkData < detail.myOverall ? detail.id : '' */
  367. let data = {
  368. challengerUserReadId: uploadRes.id,
  369. userReadId: this.data.pkData.id,
  370. }
  371. await uploadPk(data)
  372. wx.redirectTo({
  373. url: '/pages/pkResult/index'
  374. })
  375. },
  376. complete: () => {
  377. this.setData({
  378. uploadState: false
  379. })
  380. }
  381. });
  382. uploadTask.onProgressUpdate((res) => {
  383. this.setData({
  384. percent: res.progress
  385. })
  386. })
  387. },
  388. videoPlay() {
  389. if (this.data.readingReset) {
  390. this.resultAudioContext = wx.createInnerAudioContext();
  391. this.resultAudioContext.src = this.data.readDetail.tempFilePath; // 这里可以是录音的临时路径
  392. this.resultAudioContext.play();
  393. }
  394. },
  395. // 清除试听状态
  396. clearReset() {
  397. if (this.resultAudioContext) {
  398. this.resultAudioContext.stop()
  399. }
  400. this.setData({
  401. readingReset: false
  402. })
  403. },
  404. // 控制视频或音频的播放状态
  405. playMediaState() {
  406. if (!this.data.videoInfo.userReadExtend) {
  407. this.videoContext.play()
  408. } else {
  409. this.innerAudioContext.play();
  410. }
  411. },
  412. // 控制视频或音频的暂停状态
  413. stopMediaState() {
  414. if (!this.data.videoInfo.userReadExtend) {
  415. this.videoContext.stop()
  416. this.videoContext.seek(0)
  417. } else {
  418. this.innerAudioContext.stop()
  419. }
  420. },
  421. // 获取设备高度与行高度
  422. getHeight() {
  423. var query = wx.createSelectorQuery();
  424. query.select('.content').boundingClientRect((rect) => {
  425. this.setData({
  426. contentH: rect.height
  427. })
  428. }).exec()
  429. query.select('.row').boundingClientRect((rect) => {
  430. this.rowH = rect.height
  431. }).exec()
  432. },
  433. /**
  434. * 生命周期函数--监听页面卸载
  435. */
  436. onUnload() {
  437. wsEngine.reset()
  438. recorderManager.stop();
  439. if (this.innerAudioContext) {
  440. this.innerAudioContext.stop()
  441. }
  442. clearTimeout(this.setTimeoutObj)
  443. clearInterval(this.stl)
  444. },
  445. })