index.js 16 KB

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