index.js 20 KB

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