index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. wx.setNavigationBarTitle({
  128. title: videoInfo.userRead.title
  129. })
  130. let data = JSON.parse(videoInfo.userReadExtend.lessonText)
  131. data = data.map((item, index) => {
  132. item.time = Number(item.time)
  133. item.readTime = data[index + 1] ? data[index + 1].time - item.time : ''
  134. return item
  135. })
  136. this.setData({
  137. videoPath: videoInfo.userRead.originVideo,
  138. article: data,
  139. videoInfo
  140. })
  141. if (!reset) {
  142. this.getHeight()
  143. }
  144. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  145. this.videoContext = wx.createVideoContext('myVideo')
  146. } else {
  147. console.log('走了136');
  148. this.innerAudioContext.src = videoInfo.userRead.originVideo
  149. this.innerAudioContext.onEnded(res => {
  150. console.log("138innerAudioContext触发的");
  151. this.resetReading()
  152. })
  153. this.innerAudioContext.onStop((res) => {
  154. console.log("143innerAudioContext触发的");
  155. });
  156. }
  157. },
  158. // 开始录制
  159. setCountDown() {
  160. let child = this.selectComponent('#readingTips').data
  161. // 判断是否有权限朗读 不是vip并且没有朗读机会
  162. const isVip = child.vipTime ? true : false
  163. if (!isVip && child.userInfo.experienceAmount <= 0) {
  164. return this.selectComponent('#readingTips').showModal();
  165. }
  166. if (this.data.state) {
  167. this.resetReading()
  168. return
  169. }
  170. if (!this.data.readingReset) {
  171. this.getHeight()
  172. }
  173. this.resetReading()
  174. this.setData({
  175. readingReset: false,
  176. 'countDown.state': true
  177. })
  178. this.stl = setInterval(() => {
  179. if (this.data.countDown.num == 0) {
  180. clearInterval(this.stl)
  181. this.setData({
  182. state: true,
  183. countDown: {
  184. state: false,
  185. num: 3
  186. }
  187. })
  188. this.playMediaState()
  189. this.soundRecording()
  190. this.startRecording()
  191. } else {
  192. this.setData({
  193. 'countDown.num': --this.data.countDown.num
  194. })
  195. }
  196. }, 1000)
  197. },
  198. // 录音
  199. soundRecording() {
  200. console.log('zzz');
  201. /*调用微信开始录音接口,并启动语音评测*/
  202. let timeStamp = new Date().getTime()
  203. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  204. let app = {
  205. applicationId: '16075689600000da',
  206. sig, //签名字符串
  207. alg: 'sha1',
  208. timestamp: timeStamp + '',
  209. userId: wx.getStorageSync('uid')
  210. }
  211. let lessonText = JSON.parse(this.data.videoInfo.userReadExtend.lessonText).map((item) => {
  212. return item.text
  213. }).join('\n')
  214. wsEngine.start({
  215. request: {
  216. coreType: "cn.pred.raw",
  217. refText: lessonText,
  218. rank: 100,
  219. attachAudioUrl: 1,
  220. result: {
  221. details: {
  222. gop_adjust: 1
  223. }
  224. }
  225. },
  226. app,
  227. audio: {
  228. audioType: "mp3",
  229. channel: 1,
  230. sampleBytes: 2,
  231. sampleRate: 16000
  232. },
  233. success: (res) => {
  234. /*引擎启动成功,可以启动录音机开始录音,并将音频片传给引擎*/
  235. const options = {
  236. duration: 600000,
  237. sampleRate: 44100, //采样率
  238. numberOfChannels: 1, //录音通道数
  239. encodeBitRate: 192000, //编码码率
  240. format: 'mp3', //音频格式,有效值aac/mp3
  241. frameSize: 50 //指定帧大小,单位 KB
  242. };
  243. //开始录音,在开始录音回调中feed音频片
  244. recorderManager.start(options);
  245. },
  246. fail: (res) => {
  247. console.log("fail============= " + res);
  248. },
  249. });
  250. recorderManager.onError(res => {
  251. console.log(res, 'rrrrrsse');
  252. })
  253. //监听录音开始事件
  254. recorderManager.onStart(() => {});
  255. //监听录音结束事件
  256. recorderManager.onStop((res) => {
  257. console.log('录音结束', res);
  258. this.setData({
  259. tempFilePath: res.tempFilePath,
  260. });
  261. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  262. wsEngine.stop({
  263. success: () => {
  264. console.log('====== wsEngine stop success ======');
  265. },
  266. fail: (res) => {
  267. console.log('录音结束报错', res);
  268. },
  269. });
  270. });
  271. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  272. recorderManager.onFrameRecorded((res) => {
  273. const {
  274. frameBuffer
  275. } = res
  276. //TODO 调用feed接口传递音频片给驰声评测引擎
  277. wsEngine.feed({
  278. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  279. success: () => {},
  280. fail: (res) => {
  281. console.log('监听已录制完指定帧大小报错', res)
  282. },
  283. });
  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.resetReading()
  393. },
  394. videoPlay() {
  395. if (this.data.state) {
  396. return
  397. }
  398. if (this.data.videoInfo.userReadExtend.resourcesType == 1) {
  399. if (this.data.exampleState) {
  400. this.setData({
  401. exampleState: false
  402. })
  403. return this.resultAudioContext.stop()
  404. }
  405. this.resultAudioContext.src = this.data.readingReset ? this.data.readDetail.tempFilePath : this.data.videoInfo.userRead.audioPath;
  406. this.resultAudioContext.play();
  407. this.setData({
  408. exampleState: true
  409. })
  410. } else {
  411. if (this.data.readingReset) {
  412. this.resultAudioContext.src = this.data.readDetail.tempFilePath;
  413. this.resultAudioContext.play();
  414. this.setData({
  415. muted: true,
  416. exampleState: true
  417. })
  418. } else {
  419. this.setData({
  420. muted: false,
  421. exampleState: true
  422. })
  423. }
  424. this.setData({
  425. videoPath: this.data.videoInfo.userRead.videoPath
  426. })
  427. wx.nextTick(() => {
  428. this.videoContext.play()
  429. })
  430. }
  431. submitPlayLog({
  432. userReadId: this.data.videoInfo.userRead.exampleId,
  433. playStopTime: 1000
  434. })
  435. },
  436. // 控制视频或音频的播放状态
  437. async playMediaState() {
  438. console.log('触发');
  439. this.setData({
  440. muted: false
  441. })
  442. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  443. this.setData({
  444. videoPath: this.data.videoInfo.userRead.originVideo
  445. })
  446. wx.nextTick(() => {
  447. this.videoContext.play()
  448. })
  449. } else {
  450. this.innerAudioContext.play();
  451. }
  452. await userEvent({
  453. action: 'READING',
  454. readId: this.data.videoInfo.userRead.id
  455. })
  456. },
  457. // 重置一切状态
  458. resetReading() {
  459. clearTimeout(this.setTimeoutObj)
  460. clearInterval(this.stl)
  461. // 重置视频
  462. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  463. this.videoContext.stop()
  464. this.videoContext.seek(0)
  465. }
  466. // 重置试听音频
  467. if (this.data.exampleState) {
  468. this.resultAudioContext.stop()
  469. // 重置录音时的背景音乐
  470. this.innerAudioContext.stop();
  471. console.log('是我暂停了');
  472. }
  473. if (this.data.state) {
  474. // 重置录音时的背景音乐
  475. this.innerAudioContext.stop();
  476. /*微信录音结束*/
  477. recorderManager.stop();
  478. }
  479. this.setData({
  480. exampleState: false,
  481. state: false,
  482. currentRow: null,
  483. scrollTop: 0
  484. })
  485. },
  486. // 获取设备高度与行高度
  487. getHeight() {
  488. var query = wx.createSelectorQuery();
  489. query.select('.content').boundingClientRect((rect) => {
  490. this.setData({
  491. contentH: rect.height
  492. })
  493. }).exec()
  494. query.select('.row').boundingClientRect((rect) => {
  495. this.rowH = rect.height
  496. }).exec()
  497. },
  498. onHide() {
  499. this.resetReading()
  500. },
  501. onUnload() {
  502. this.resetReading()
  503. this.storeBindings.destroyStoreBindings()
  504. },
  505. creatShare() {
  506. return new Promise((resolve, reject) => {
  507. let video = this.data.videoInfo
  508. let context = wx.createSelectorQuery();
  509. context
  510. .select('#share')
  511. .fields({
  512. node: true,
  513. size: true
  514. }).exec((res) => {
  515. const canvas = res[0].node;
  516. const ctx = canvas.getContext('2d');
  517. const dpr = wx.getSystemInfoSync().pixelRatio;
  518. canvas.width = res[0].width * dpr;
  519. canvas.height = res[0].height * dpr;
  520. ctx.scale(dpr, dpr);
  521. ctx.font = '14px PingFang';
  522. let pic = canvas.createImage();
  523. pic.src = video.userReadExtend && video.userReadExtend.resourcesType == 1 ? video.userReadExtend.backgroundVirtualImg : video.userRead.coverImg;
  524. pic.onload = () => {
  525. ctx.drawImage(pic, 0, 0, 375, 211);
  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. if (video.userReadExtend.resourcesType == 1) {
  555. let aBg = canvas.createImage();
  556. aBg.src = '/static/shareAudioBg.png';
  557. aBg.onload = () => {
  558. ctx.drawImage(aBg, 127.5, 38, 120, 120);
  559. let rate = 0.5
  560. ctx.arc(
  561. Math.floor(375 * rate),
  562. 98,
  563. Math.floor(100 * rate),
  564. 0,
  565. 2 * Math.PI
  566. );
  567. ctx.clip() //裁剪
  568. let coverImg = canvas.createImage();
  569. coverImg.src = video.userRead.coverImg;
  570. coverImg.onload = () => {
  571. ctx.drawImage( //定位在圆圈范围内便会出现
  572. coverImg, //图片暂存路径
  573. 129, 42,
  574. 110, 110,
  575. );
  576. ctx.restore()
  577. }
  578. }
  579. }
  580. setTimeout(() => {
  581. wx.canvasToTempFilePath({
  582. canvas: canvas,
  583. success(res) {
  584. resolve({
  585. title: '我的新作品发布啦,快来捧场点赞!',
  586. path: `/pages/pkPage/index?videoId=${wx.getStorageSync('shareVideoId')}&uid=${wx.getStorageSync('uid')}`,
  587. imageUrl: res.tempFilePath
  588. })
  589. },
  590. fail(res) {
  591. reject()
  592. }
  593. }, this)
  594. }, 500)
  595. }
  596. }
  597. }
  598. }
  599. }
  600. }
  601. })
  602. })
  603. },
  604. onShareAppMessage({
  605. from,
  606. target
  607. }) {
  608. if (from == 'button') {
  609. const promise = new Promise(resolve => {
  610. this.creatShare().then(res => {
  611. resolve(res)
  612. })
  613. })
  614. return {
  615. title: '我的新作品发布啦,快来捧场点赞!',
  616. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  617. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg',
  618. promise
  619. }
  620. } else {
  621. return {
  622. title: '自从用了它,家里朗朗书声,美妙极了!你家孩子也快来试试!',
  623. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  624. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg'
  625. }
  626. }
  627. },
  628. })