index.js 18 KB

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