index.js 18 KB

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