index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import {
  2. getreadInfo
  3. } from '~/api/video'
  4. import {
  5. publishWorks,
  6. uploadPk,
  7. postWorksScore
  8. } from '~/api/works'
  9. import {
  10. userEvent
  11. } from '~/api/global'
  12. import {
  13. createStoreBindings
  14. } from 'mobx-miniprogram-bindings'
  15. import {
  16. store
  17. } from '~/store/index'
  18. const aiengine = require('~/utils/ChivoxAiEngine')
  19. const sha1 = require('~/utils/sha1');
  20. // 文章行高
  21. let rowH = 0
  22. let videoContext = null
  23. // 滚动变色定时器
  24. let stl = null
  25. // 倒计时
  26. let setTimeoutObj = null
  27. // 录音
  28. let innerAudioContext = null
  29. // 试听
  30. let resultAudioContext = null
  31. /*创建基础引擎*/
  32. let wsEngine = aiengine.createWsEngine({});
  33. /*微信录音*/
  34. let recorderManager = wx.getRecorderManager();
  35. Page({
  36. data: {
  37. videoInfo: {},
  38. currentRow: null,
  39. state: false,
  40. // 示例播放状态
  41. exampleState: false,
  42. // 是否静音播放视频
  43. muted: false,
  44. countDown: {
  45. state: false,
  46. num: 3,
  47. },
  48. contentH: 0,
  49. scrollTop: 0,
  50. //如果readingReset为true就是重读
  51. readingReset: false,
  52. //readingType为public是普通阅读,为pk是pk逻辑,readMatch为朗读赛
  53. readingType: 'public',
  54. percent: 0,
  55. uploadState: false,
  56. article: []
  57. },
  58. onLoad(options) {
  59. let videoId = options.videoId
  60. this.getreadInfo(videoId, options.reset)
  61. this.setData({
  62. readingReset: options.reset || false,
  63. readingType: options.readingType || 'public',
  64. uploadHide: options.uploadHide
  65. })
  66. // 手工绑定
  67. this.storeBindings = createStoreBindings(this, {
  68. store,
  69. fields: {
  70. userInfo: 'userInfo',
  71. readDetail: 'readDetail',
  72. pkData: 'pkData'
  73. },
  74. actions: {
  75. setReadDetail: 'setReadDetail'
  76. }
  77. })
  78. // 录音授权
  79. wx.getSetting({
  80. success(res) {
  81. if (!res.authSetting['scope.record']) {
  82. wx.authorize({
  83. scope: 'scope.record',
  84. success() {
  85. // 用户已经同意小程序使用录音功能,后续调用接口不会弹窗询问
  86. wx.getRecorderManager()
  87. }
  88. })
  89. }
  90. }
  91. })
  92. /*监听评测结果:必须在基础引擎创建后,调用任何评测接口前设置监听,否则有可能收不到相关事件。*/
  93. wsEngine.onResult((res) => {
  94. this.getRecordScore(res)
  95. });
  96. wsEngine.onErrorResult((res) => {
  97. console.log("===收到错误结果=============", res)
  98. });
  99. this.innerAudioContext = wx.createInnerAudioContext();
  100. this.resultAudioContext = wx.createInnerAudioContext();
  101. this.resultAudioContext.onEnded(res => {
  102. this.setData({
  103. exampleState: false
  104. })
  105. this.stopMediaState()
  106. })
  107. this.resultAudioContext.onStop((res) => {
  108. this.setData({
  109. exampleState: false
  110. })
  111. this.stopMediaState()
  112. });
  113. },
  114. // 获取阅读内容
  115. async getreadInfo(videoId, reset = false) {
  116. let videoInfo = await getreadInfo(videoId)
  117. wx.setNavigationBarTitle({
  118. title: videoInfo.userRead.title
  119. })
  120. let data = JSON.parse(videoInfo.userReadExtend.lessonText)
  121. data = data.map((item, index) => {
  122. item.time = Number(item.time)
  123. item.readTime = data[index + 1] ? data[index + 1].time - item.time : ''
  124. return item
  125. })
  126. this.setData({
  127. article: data,
  128. videoInfo
  129. })
  130. if (!reset) {
  131. this.getHeight()
  132. }
  133. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  134. this.videoContext = wx.createVideoContext('myVideo')
  135. } else {
  136. this.innerAudioContext.src = videoInfo.userRead.originVideo
  137. this.innerAudioContext.onEnded(res => {
  138. console.log("138innerAudioContext触发的");
  139. this.finishRecord()
  140. })
  141. this.innerAudioContext.onStop((res) => {
  142. console.log("143innerAudioContext触发的");
  143. this.finishRecord()
  144. });
  145. }
  146. },
  147. // 开始录制
  148. setCountDown() {
  149. let child = this.selectComponent('#readingTips').data
  150. // 判断是否有权限朗读 不是vip并且没有朗读机会
  151. const isVip = child.vipTime ? true : false
  152. if (!isVip && child.userInfo.experienceAmount <= 0) {
  153. return this.selectComponent('#readingTips').showModal();
  154. }
  155. if (this.data.state) {
  156. this.finishRecord()
  157. return
  158. }
  159. if (!this.data.readingReset) {
  160. this.getHeight()
  161. }
  162. this.stopMediaState()
  163. this.setData({
  164. readingReset: false,
  165. 'countDown.state': true
  166. })
  167. this.stl = setInterval(() => {
  168. if (this.data.countDown.num == 0) {
  169. clearInterval(this.stl)
  170. this.setData({
  171. state: true,
  172. countDown: {
  173. state: false,
  174. num: 3
  175. }
  176. })
  177. this.soundRecording()
  178. this.playMediaState()
  179. this.startRecording()
  180. } else {
  181. this.setData({
  182. 'countDown.num': --this.data.countDown.num
  183. })
  184. }
  185. }, 1000)
  186. },
  187. // 录音
  188. soundRecording() {
  189. /*调用微信开始录音接口,并启动语音评测*/
  190. let timeStamp = new Date().getTime()
  191. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  192. let app = {
  193. applicationId: '16075689600000da',
  194. sig, //签名字符串
  195. alg: 'sha1',
  196. timestamp: timeStamp + '',
  197. userId: wx.getStorageSync('uid')
  198. }
  199. let lessonText = JSON.parse(this.data.videoInfo.userReadExtend.lessonText).map((item) => {
  200. return item.text
  201. }).join('\n')
  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. recorderManager.onError(res => {
  238. console.log(res, 'rrrrrsse');
  239. })
  240. //监听录音开始事件
  241. recorderManager.onStart(() => {});
  242. //监听录音结束事件
  243. recorderManager.onStop((res) => {
  244. console.log('录音结束', res);
  245. this.setData({
  246. tempFilePath: res.tempFilePath,
  247. });
  248. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  249. wsEngine.stop({
  250. success: () => {
  251. console.log('====== wsEngine stop success ======');
  252. },
  253. fail: (res) => {
  254. console.log('录音结束报错', res);
  255. },
  256. });
  257. });
  258. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  259. recorderManager.onFrameRecorded((res) => {
  260. const {
  261. frameBuffer
  262. } = res
  263. //TODO 调用feed接口传递音频片给驰声评测引擎
  264. wsEngine.feed({
  265. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  266. success: () => {},
  267. fail: (res) => {
  268. console.log('监听已录制完指定帧大小报错', res)
  269. },
  270. });
  271. });
  272. },
  273. // 结束录制
  274. finishRecord() {
  275. console.log('触发结束录制了');
  276. recorderManager.stop();
  277. this.stopMediaState()
  278. clearTimeout(this.setTimeoutObj)
  279. clearInterval(this.stl)
  280. this.setData({
  281. state: false,
  282. currentRow: null,
  283. scrollTop: 0
  284. })
  285. },
  286. // 获取测评结果
  287. getRecordScore(res) {
  288. const result = res.result;
  289. const integrity = Math.floor(result.integrity); //完成度
  290. const tone = Math.floor(result.tone); // 语调声调
  291. const accuracy = Math.floor(result.overall); // 准确度 发音分
  292. const fluency = Math.floor(result.fluency.overall); //流利度
  293. let myOverall = Math.floor(integrity * 0.3 + accuracy * 0.5 + fluency * 0.1 + tone * 0.1);
  294. let detail = {
  295. integrity,
  296. tone,
  297. accuracy,
  298. fluency,
  299. myOverall,
  300. tempFilePath: this.data.tempFilePath,
  301. title: this.data.videoInfo.userRead.title,
  302. id: this.data.videoInfo.userRead.exampleId,
  303. coverImg: this.data.videoInfo.userRead.coverImg,
  304. resourcesType: this.data.videoInfo.userReadExtend.resourcesType,
  305. aBg: this.data.videoInfo.userReadExtend.resourcesType == 1 ? this.data.videoInfo.userReadExtend.backgroundVirtualImg : '',
  306. originVideo: this.data.videoInfo.userRead.originVideo
  307. }
  308. this.setReadDetail(detail)
  309. if (this.data.readingType == 'public' || this.data.readingType == 'readMatch') {
  310. wx.redirectTo({
  311. url: `/pages/score/index?readingType=${this.data.readingType}`
  312. })
  313. } else {
  314. this.uploadAudio(detail)
  315. }
  316. },
  317. // 挑战录音上传
  318. uploadAudio(detail) {
  319. this.setData({
  320. uploadState: true
  321. })
  322. const uploadTask = wx.uploadFile({
  323. url: 'https://reader-api.ai160.com//file/upload',
  324. filePath: this.data.tempFilePath,
  325. name: '朗读录音',
  326. header: {
  327. uid: wx.getStorageSync('uid')
  328. },
  329. success: async (res) => {
  330. const formateRes = JSON.parse(res.data);
  331. let audioPath = formateRes.data;
  332. let uploadRes = await publishWorks({
  333. exampleId: this.data.pkData.exampleId,
  334. audioPath
  335. })
  336. let _data = this.data.readDetail
  337. postWorksScore({
  338. "userReadId": uploadRes.id,
  339. "complete": _data.integrity,
  340. "accuracy": _data.accuracy,
  341. "speed": _data.fluency,
  342. "intonation": _data.tone,
  343. "score": _data.myOverall
  344. })
  345. let data = {
  346. challengerUserReadId: uploadRes.id,
  347. userReadId: this.data.pkData.id,
  348. winnerUId: this.data.pkData.score > _data.myOverall ? this.data.pkData.uid : this.data.pkData.score == _data.myOverall ? '' : wx.getStorageSync('uid')
  349. }
  350. let result = await uploadPk(data)
  351. wx.redirectTo({
  352. url: `/pages/pkResult/index?id=${result.id}`
  353. })
  354. },
  355. complete: () => {
  356. this.setData({
  357. uploadState: false
  358. })
  359. }
  360. });
  361. uploadTask.onProgressUpdate((res) => {
  362. this.setData({
  363. percent: res.progress
  364. })
  365. })
  366. },
  367. // 字体换行
  368. startRecording() {
  369. if (this.data.currentRow == null) {
  370. this.setData({
  371. currentRow: 0
  372. })
  373. }
  374. let row = this.data.article[this.data.currentRow]
  375. if (!row.readTime) {
  376. return
  377. }
  378. this.setTimeoutObj = setTimeout(() => {
  379. this.setData({
  380. currentRow: ++this.data.currentRow
  381. })
  382. this.setData({
  383. scrollTop: this.rowH * this.data.currentRow
  384. })
  385. this.startRecording()
  386. },
  387. row.readTime);
  388. },
  389. // 视频播放结束
  390. videoEnd() {
  391. console.log('视频播放结束触发的');
  392. this.finishRecord()
  393. },
  394. videoPlay() {
  395. if (this.data.videoInfo.userReadExtend.resourcesType == 1) {
  396. if (this.data.exampleState) {
  397. this.setData({
  398. exampleState: false
  399. })
  400. return this.resultAudioContext.stop()
  401. }
  402. this.resultAudioContext.src = this.data.readingReset ? this.data.readDetail.tempFilePath : this.data.videoInfo.userRead.audioPath;
  403. this.resultAudioContext.play();
  404. this.setData({
  405. exampleState: true
  406. })
  407. } else {
  408. if (this.data.readingReset) {
  409. this.resultAudioContext.src = this.data.readDetail.tempFilePath;
  410. this.resultAudioContext.play();
  411. this.setData({
  412. muted: true,
  413. exampleState: true
  414. })
  415. } else {
  416. this.setData({
  417. muted: false,
  418. exampleState: true
  419. })
  420. }
  421. this.videoContext.play()
  422. }
  423. /* if (!this.data.readingReset) {
  424. this.startRecording()
  425. } */
  426. },
  427. // 控制视频或音频的播放状态
  428. async playMediaState() {
  429. this.setData({
  430. muted: false
  431. })
  432. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  433. this.videoContext.play()
  434. } else {
  435. this.innerAudioContext.play();
  436. }
  437. await userEvent({
  438. action: 'READING',
  439. readId: this.data.videoInfo.userRead.id
  440. })
  441. },
  442. // 控制视频或音频的暂停状态
  443. stopMediaState() {
  444. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  445. this.videoContext.stop()
  446. this.videoContext.seek(0)
  447. }
  448. this.innerAudioContext.stop()
  449. this.resultAudioContext.stop()
  450. },
  451. // 获取设备高度与行高度
  452. getHeight() {
  453. var query = wx.createSelectorQuery();
  454. query.select('.content').boundingClientRect((rect) => {
  455. this.setData({
  456. contentH: rect.height
  457. })
  458. }).exec()
  459. query.select('.row').boundingClientRect((rect) => {
  460. this.rowH = rect.height
  461. }).exec()
  462. },
  463. onHide() {
  464. wsEngine.reset()
  465. if (this.innerAudioContext) {
  466. this.innerAudioContext.stop()
  467. }
  468. this.finishRecord()
  469. },
  470. onUnload() {
  471. wsEngine.reset()
  472. if (this.innerAudioContext) {
  473. this.innerAudioContext.stop()
  474. }
  475. this.finishRecord()
  476. },
  477. creatShare() {
  478. return new Promise((resolve, reject) => {
  479. let video = this.data.videoInfo
  480. let context = wx.createSelectorQuery();
  481. context
  482. .select('#share')
  483. .fields({
  484. node: true,
  485. size: true
  486. }).exec((res) => {
  487. const canvas = res[0].node;
  488. const ctx = canvas.getContext('2d');
  489. const dpr = wx.getSystemInfoSync().pixelRatio;
  490. canvas.width = res[0].width * dpr;
  491. canvas.height = res[0].height * dpr;
  492. ctx.scale(dpr, dpr);
  493. ctx.font = '14px PingFang';
  494. let pic = canvas.createImage();
  495. pic.src = video.userReadExtend && video.userReadExtend.resourcesType == 1 ? video.userReadExtend.backgroundVirtualImg : video.userRead.coverImg;
  496. pic.onload = () => {
  497. ctx.drawImage(pic, 0, 0, 375, 211);
  498. if (video.userReadExtend.resourcesType == 1) {
  499. let aBg = canvas.createImage();
  500. aBg.src = '/static/shareAudioBg.png';
  501. aBg.onload = () => {
  502. ctx.drawImage(aBg, 127.5, 38, 120, 120);
  503. let rate = 0.5
  504. ctx.arc(
  505. Math.floor(375 * rate),
  506. 98,
  507. Math.floor(100 * rate),
  508. 0,
  509. 2 * Math.PI
  510. );
  511. ctx.clip() //裁剪
  512. let coverImg = canvas.createImage();
  513. coverImg.src = video.userRead.coverImg;
  514. coverImg.onload = () => {
  515. ctx.drawImage( //定位在圆圈范围内便会出现
  516. coverImg, //图片暂存路径
  517. 129, 42,
  518. 110, 110,
  519. );
  520. ctx.restore()
  521. }
  522. }
  523. }
  524. }
  525. let peiyin = canvas.createImage();
  526. peiyin.src = '/static/peiyin.jpg';
  527. peiyin.onload = () => {
  528. ctx.drawImage(peiyin, 0, 211, 375, 89);
  529. //分享
  530. let fx = canvas.createImage();
  531. fx.src = '/static/share.png'
  532. fx.onload = () => {
  533. ctx.drawImage(fx, 12, 220, 20, 20)
  534. ctx.fillText('分享', 36, 238)
  535. // 收藏,一个一个渲染
  536. let sc = canvas.createImage();
  537. sc.src = '/static/no_collect.png'
  538. sc.onload = () => {
  539. ctx.drawImage(sc, 110, 220, 19, 19)
  540. ctx.fillText('收藏', 134, 238)
  541. //点赞
  542. let dz = canvas.createImage();
  543. dz.src = '/static/heart.png'
  544. dz.onload = () => {
  545. ctx.drawImage(dz, 318, 222, 22, 22)
  546. ctx.fillText(0, 254, 238)
  547. // 评论
  548. let pl = canvas.createImage();
  549. pl.src = '/static/comment.png'
  550. pl.onload = () => {
  551. ctx.drawImage(pl, 228, 222, 22, 22)
  552. ctx.fillText(0, 340, 238)
  553. setTimeout(() => {
  554. wx.canvasToTempFilePath({
  555. canvas: canvas,
  556. success(res) {
  557. resolve({
  558. title: '我的新作品发布啦,快来捧场点赞!',
  559. path: `/pages/pkPage/index?videoId=${wx.getStorageSync('shareVideoId')}&uid=${wx.getStorageSync('uid')}`,
  560. imageUrl: res.tempFilePath
  561. })
  562. },
  563. fail(res) {
  564. reject()
  565. }
  566. }, this)
  567. }, 500)
  568. }
  569. }
  570. }
  571. }
  572. }
  573. })
  574. })
  575. },
  576. onShareAppMessage({
  577. from,
  578. target
  579. }) {
  580. if (from == 'button') {
  581. const promise = new Promise(resolve => {
  582. this.creatShare().then(res => {
  583. resolve(res)
  584. })
  585. })
  586. return {
  587. title: '请欣赏我的课文朗读作品,点赞+评论。',
  588. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  589. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png',
  590. promise
  591. }
  592. } else {
  593. return {
  594. title: '课文朗读,从未如此有趣。',
  595. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  596. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png'
  597. }
  598. }
  599. },
  600. })