index.js 19 KB

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