index.js 20 KB

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