index.js 12 KB

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