index.js 12 KB

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