index.js 17 KB

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