index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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.playMediaState()
  178. this.soundRecording()
  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. duration: 600000,
  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. recorderManager.onError(res => {
  239. console.log(res, 'rrrrrsse');
  240. })
  241. //监听录音开始事件
  242. recorderManager.onStart(() => {});
  243. //监听录音结束事件
  244. recorderManager.onStop((res) => {
  245. console.log('录音结束', res);
  246. this.setData({
  247. tempFilePath: res.tempFilePath,
  248. });
  249. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  250. wsEngine.stop({
  251. success: () => {
  252. console.log('====== wsEngine stop success ======');
  253. },
  254. fail: (res) => {
  255. console.log('录音结束报错', res);
  256. },
  257. });
  258. });
  259. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  260. recorderManager.onFrameRecorded((res) => {
  261. const {
  262. frameBuffer
  263. } = res
  264. //TODO 调用feed接口传递音频片给驰声评测引擎
  265. wsEngine.feed({
  266. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  267. success: () => {},
  268. fail: (res) => {
  269. console.log('监听已录制完指定帧大小报错', res)
  270. },
  271. });
  272. });
  273. },
  274. // 结束录制
  275. finishRecord() {
  276. console.log('触发结束录制了');
  277. recorderManager.stop();
  278. this.stopMediaState()
  279. clearTimeout(this.setTimeoutObj)
  280. clearInterval(this.stl)
  281. this.setData({
  282. state: false,
  283. currentRow: null,
  284. scrollTop: 0
  285. })
  286. },
  287. // 获取测评结果
  288. getRecordScore(res) {
  289. const result = res.result;
  290. const integrity = Math.floor(result.integrity); //完成度
  291. const tone = Math.floor(result.tone); // 语调声调
  292. const accuracy = Math.floor(result.overall); // 准确度 发音分
  293. const fluency = Math.floor(result.fluency.overall); //流利度
  294. let myOverall = Math.floor(integrity * 0.3 + accuracy * 0.5 + fluency * 0.1 + tone * 0.1);
  295. let detail = {
  296. integrity,
  297. tone,
  298. accuracy,
  299. fluency,
  300. myOverall,
  301. tempFilePath: this.data.tempFilePath,
  302. title: this.data.videoInfo.userRead.title,
  303. id: this.data.videoInfo.userRead.exampleId,
  304. coverImg: this.data.videoInfo.userRead.coverImg,
  305. resourcesType: this.data.videoInfo.userReadExtend.resourcesType,
  306. aBg: this.data.videoInfo.userReadExtend.resourcesType == 1 ? this.data.videoInfo.userReadExtend.backgroundVirtualImg : '',
  307. originVideo: this.data.videoInfo.userRead.originVideo
  308. }
  309. this.setReadDetail(detail)
  310. if (this.data.readingType == 'public' || this.data.readingType == 'readMatch') {
  311. wx.redirectTo({
  312. url: `/pages/score/index?readingType=${this.data.readingType}`
  313. })
  314. } else {
  315. this.uploadAudio(detail)
  316. }
  317. },
  318. // 挑战录音上传
  319. uploadAudio(detail) {
  320. this.setData({
  321. uploadState: true
  322. })
  323. const uploadTask = wx.uploadFile({
  324. url: 'https://reader-api.ai160.com//file/upload',
  325. filePath: this.data.tempFilePath,
  326. name: '朗读录音',
  327. header: {
  328. uid: wx.getStorageSync('uid')
  329. },
  330. success: async (res) => {
  331. const formateRes = JSON.parse(res.data);
  332. let audioPath = formateRes.data;
  333. let uploadRes = await publishWorks({
  334. exampleId: this.data.pkData.exampleId,
  335. audioPath
  336. })
  337. let _data = this.data.readDetail
  338. postWorksScore({
  339. "userReadId": uploadRes.id,
  340. "complete": _data.integrity,
  341. "accuracy": _data.accuracy,
  342. "speed": _data.fluency,
  343. "intonation": _data.tone,
  344. "score": _data.myOverall
  345. })
  346. let data = {
  347. challengerUserReadId: uploadRes.id,
  348. userReadId: this.data.pkData.id,
  349. winnerUId: this.data.pkData.score > _data.myOverall ? this.data.pkData.uid : this.data.pkData.score == _data.myOverall ? '' : wx.getStorageSync('uid')
  350. }
  351. let result = await uploadPk(data)
  352. wx.redirectTo({
  353. url: `/pages/pkResult/index?id=${result.id}`
  354. })
  355. },
  356. complete: () => {
  357. this.setData({
  358. uploadState: false
  359. })
  360. }
  361. });
  362. uploadTask.onProgressUpdate((res) => {
  363. this.setData({
  364. percent: res.progress
  365. })
  366. })
  367. },
  368. // 字体换行
  369. startRecording() {
  370. if (this.data.currentRow == null) {
  371. this.setData({
  372. currentRow: 0
  373. })
  374. }
  375. let row = this.data.article[this.data.currentRow]
  376. if (!row.readTime) {
  377. return
  378. }
  379. this.setTimeoutObj = setTimeout(() => {
  380. this.setData({
  381. currentRow: ++this.data.currentRow
  382. })
  383. this.setData({
  384. scrollTop: this.rowH * this.data.currentRow
  385. })
  386. this.startRecording()
  387. },
  388. row.readTime);
  389. },
  390. // 视频播放结束
  391. videoEnd() {
  392. console.log('视频播放结束触发的');
  393. this.finishRecord()
  394. },
  395. videoPlay() {
  396. if (this.data.videoInfo.userReadExtend.resourcesType == 1) {
  397. if (this.data.exampleState) {
  398. this.setData({
  399. exampleState: false
  400. })
  401. return this.resultAudioContext.stop()
  402. }
  403. this.resultAudioContext.src = this.data.readingReset ? this.data.readDetail.tempFilePath : this.data.videoInfo.userRead.audioPath;
  404. this.resultAudioContext.play();
  405. this.setData({
  406. exampleState: true
  407. })
  408. } else {
  409. if (this.data.readingReset) {
  410. this.resultAudioContext.src = this.data.readDetail.tempFilePath;
  411. this.resultAudioContext.play();
  412. this.setData({
  413. muted: true,
  414. exampleState: true
  415. })
  416. } else {
  417. this.setData({
  418. muted: false,
  419. exampleState: true
  420. })
  421. }
  422. this.videoContext.play()
  423. }
  424. /* if (!this.data.readingReset) {
  425. this.startRecording()
  426. } */
  427. },
  428. // 控制视频或音频的播放状态
  429. async playMediaState() {
  430. this.setData({
  431. muted: false
  432. })
  433. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  434. this.videoContext.play()
  435. } else {
  436. this.innerAudioContext.play();
  437. }
  438. await userEvent({
  439. action: 'READING',
  440. readId: this.data.videoInfo.userRead.id
  441. })
  442. },
  443. // 控制视频或音频的暂停状态
  444. stopMediaState() {
  445. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  446. this.videoContext.stop()
  447. this.videoContext.seek(0)
  448. }
  449. this.innerAudioContext.stop()
  450. this.resultAudioContext.stop()
  451. },
  452. // 获取设备高度与行高度
  453. getHeight() {
  454. var query = wx.createSelectorQuery();
  455. query.select('.content').boundingClientRect((rect) => {
  456. this.setData({
  457. contentH: rect.height
  458. })
  459. }).exec()
  460. query.select('.row').boundingClientRect((rect) => {
  461. this.rowH = rect.height
  462. }).exec()
  463. },
  464. onHide() {
  465. wsEngine.reset()
  466. if (this.innerAudioContext) {
  467. this.innerAudioContext.stop()
  468. }
  469. this.finishRecord()
  470. },
  471. onUnload() {
  472. wsEngine.reset()
  473. if (this.innerAudioContext) {
  474. this.innerAudioContext.stop()
  475. }
  476. this.finishRecord()
  477. },
  478. creatShare() {
  479. return new Promise((resolve, reject) => {
  480. let video = this.data.videoInfo
  481. let context = wx.createSelectorQuery();
  482. context
  483. .select('#share')
  484. .fields({
  485. node: true,
  486. size: true
  487. }).exec((res) => {
  488. const canvas = res[0].node;
  489. const ctx = canvas.getContext('2d');
  490. const dpr = wx.getSystemInfoSync().pixelRatio;
  491. canvas.width = res[0].width * dpr;
  492. canvas.height = res[0].height * dpr;
  493. ctx.scale(dpr, dpr);
  494. ctx.font = '14px PingFang';
  495. let pic = canvas.createImage();
  496. pic.src = video.userReadExtend && video.userReadExtend.resourcesType == 1 ? video.userReadExtend.backgroundVirtualImg : video.userRead.coverImg;
  497. pic.onload = () => {
  498. ctx.drawImage(pic, 0, 0, 375, 211);
  499. if (video.userReadExtend.resourcesType == 1) {
  500. let aBg = canvas.createImage();
  501. aBg.src = '/static/shareAudioBg.png';
  502. aBg.onload = () => {
  503. ctx.drawImage(aBg, 127.5, 38, 120, 120);
  504. let rate = 0.5
  505. ctx.arc(
  506. Math.floor(375 * rate),
  507. 98,
  508. Math.floor(100 * rate),
  509. 0,
  510. 2 * Math.PI
  511. );
  512. ctx.clip() //裁剪
  513. let coverImg = canvas.createImage();
  514. coverImg.src = video.userRead.coverImg;
  515. coverImg.onload = () => {
  516. ctx.drawImage( //定位在圆圈范围内便会出现
  517. coverImg, //图片暂存路径
  518. 129, 42,
  519. 110, 110,
  520. );
  521. ctx.restore()
  522. }
  523. }
  524. }
  525. }
  526. let peiyin = canvas.createImage();
  527. peiyin.src = '/static/peiyin.jpg';
  528. peiyin.onload = () => {
  529. ctx.drawImage(peiyin, 0, 211, 375, 89);
  530. //分享
  531. let fx = canvas.createImage();
  532. fx.src = '/static/share.png'
  533. fx.onload = () => {
  534. ctx.drawImage(fx, 12, 220, 20, 20)
  535. ctx.fillText('分享', 36, 238)
  536. // 收藏,一个一个渲染
  537. let sc = canvas.createImage();
  538. sc.src = '/static/no_collect.png'
  539. sc.onload = () => {
  540. ctx.drawImage(sc, 110, 220, 19, 19)
  541. ctx.fillText('收藏', 134, 238)
  542. //点赞
  543. let dz = canvas.createImage();
  544. dz.src = '/static/heart.png'
  545. dz.onload = () => {
  546. ctx.drawImage(dz, 318, 222, 22, 22)
  547. ctx.fillText(0, 254, 238)
  548. // 评论
  549. let pl = canvas.createImage();
  550. pl.src = '/static/comment.png'
  551. pl.onload = () => {
  552. ctx.drawImage(pl, 228, 222, 22, 22)
  553. ctx.fillText(0, 340, 238)
  554. setTimeout(() => {
  555. wx.canvasToTempFilePath({
  556. canvas: canvas,
  557. success(res) {
  558. resolve({
  559. title: '我的新作品发布啦,快来捧场点赞!',
  560. path: `/pages/pkPage/index?videoId=${wx.getStorageSync('shareVideoId')}&uid=${wx.getStorageSync('uid')}`,
  561. imageUrl: res.tempFilePath
  562. })
  563. },
  564. fail(res) {
  565. reject()
  566. }
  567. }, this)
  568. }, 500)
  569. }
  570. }
  571. }
  572. }
  573. }
  574. })
  575. })
  576. },
  577. onShareAppMessage({
  578. from,
  579. target
  580. }) {
  581. if (from == 'button') {
  582. const promise = new Promise(resolve => {
  583. this.creatShare().then(res => {
  584. resolve(res)
  585. })
  586. })
  587. return {
  588. title: '请欣赏我的课文朗读作品,点赞+评论。',
  589. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  590. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png',
  591. promise
  592. }
  593. } else {
  594. return {
  595. title: '课文朗读,从未如此有趣。',
  596. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  597. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png'
  598. }
  599. }
  600. },
  601. })