index.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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. buyVip,
  12. getVipInfo
  13. } from '~/api/user'
  14. import {
  15. userEvent
  16. } from '~/api/global'
  17. import {
  18. createStoreBindings
  19. } from 'mobx-miniprogram-bindings'
  20. import {
  21. store
  22. } from '~/store/index'
  23. import {
  24. setDuration
  25. } from '~/utils/util'
  26. const aiengine = require('~/utils/ChivoxAiEngine')
  27. const sha1 = require('~/utils/sha1');
  28. // 文章行高
  29. let rowH = 0
  30. let videoContext = null
  31. // 滚动变色定时器
  32. let stl = null
  33. // 倒计时
  34. let setTimeoutObj = null
  35. // 录音
  36. let innerAudioContext = null
  37. // 试听
  38. let resultAudioContext = null
  39. /*创建基础引擎*/
  40. let wsEngine = aiengine.createWsEngine({});
  41. /*微信录音*/
  42. let recorderManager = wx.getRecorderManager();
  43. Page({
  44. data: {
  45. videoInfo: {},
  46. videoPath: '',
  47. currentRow: null,
  48. state: false,
  49. // 示例播放状态
  50. exampleState: false,
  51. // 是否静音播放视频
  52. muted: false,
  53. countDown: {
  54. state: false,
  55. num: 3,
  56. },
  57. contentH: 0,
  58. scrollTop: 0,
  59. //如果readingReset为true就是重读
  60. readingReset: false,
  61. //readingType为public是普通阅读,为pk是pk逻辑,readMatch为朗读赛
  62. readingType: 'public',
  63. percent: 0,
  64. uploadState: false,
  65. article: [],
  66. silderData: {
  67. currentTime: '00:00',
  68. endTime: '00:00',
  69. silderValue: 0
  70. },
  71. // 朗读赛的id
  72. activityId: '',
  73. isVip: false
  74. },
  75. onLoad(options) {
  76. console.log(options);
  77. let videoId = options.videoId
  78. wx.setNavigationBarTitle({
  79. title: options.navBarTitle
  80. })
  81. this.getreadInfo(videoId, options.reset).then(res => {
  82. wx.nextTick(() => {
  83. if (options.voluntarily && this.data.isVip) {
  84. this.setCountDown()
  85. }
  86. if (options.autoPlay) {
  87. this.videoPlay()
  88. }
  89. })
  90. })
  91. this.setData({
  92. readingReset: options.reset || false,
  93. readingType: options.readingType || 'public',
  94. uploadHide: options.uploadHide,
  95. activityId: options.activityId || '',
  96. })
  97. // 手工绑定
  98. this.storeBindings = createStoreBindings(this, {
  99. store,
  100. fields: {
  101. userInfo: 'userInfo',
  102. readDetail: 'readDetail',
  103. pkData: 'pkData'
  104. },
  105. actions: {
  106. setReadDetail: 'setReadDetail'
  107. }
  108. })
  109. // 录音授权
  110. wx.getSetting({
  111. success(res) {
  112. if (!res.authSetting['scope.record']) {
  113. wx.authorize({
  114. scope: 'scope.record',
  115. success() {
  116. // 用户已经同意小程序使用录音功能,后续调用接口不会弹窗询问
  117. },
  118. fail() {
  119. wx.showModal({
  120. title: '授权提示',
  121. content: '请先开启录音功能',
  122. success(res) {
  123. wx.openSetting({
  124. success(res) {}
  125. })
  126. }
  127. })
  128. }
  129. })
  130. }
  131. }
  132. })
  133. /*监听评测结果:必须在基础引擎创建后,调用任何评测接口前设置监听,否则有可能收不到相关事件。*/
  134. wsEngine.onResult((res) => {
  135. this.getRecordScore(res)
  136. });
  137. wsEngine.onErrorResult(async (res) => {
  138. console.log("===收到错误结果=============", res)
  139. await userEvent({
  140. action: 'WXSCORE',
  141. targetContent: res
  142. })
  143. });
  144. this.innerAudioContext = wx.createInnerAudioContext();
  145. this.innerAudioContext.onTimeUpdate(res => {
  146. this.setData({
  147. ["silderData.sliderValue"]: Math.round(this.innerAudioContext.currentTime / this.innerAudioContext.duration * 100),
  148. ["silderData.currentTime"]: setDuration(this.innerAudioContext.currentTime)
  149. })
  150. })
  151. this.resultAudioContext = wx.createInnerAudioContext();
  152. this.resultAudioContext.onTimeUpdate(res => {
  153. this.setData({
  154. ["silderData.sliderValue"]: Math.round(this.resultAudioContext.currentTime / this.resultAudioContext.duration * 100),
  155. ["silderData.currentTime"]: setDuration(this.resultAudioContext.currentTime)
  156. })
  157. })
  158. this.resultAudioContext.onError(res => {
  159. console.log(res, 'resultAudioContext');
  160. })
  161. this.innerAudioContext.onError(res => {
  162. console.log(res, 'bbbb');
  163. })
  164. this.resultAudioContext.onEnded(res => {
  165. console.log('102-resultAudioContext.ended');
  166. this.setData({
  167. exampleState: false
  168. })
  169. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  170. this.videoContext.stop()
  171. this.videoContext.seek(0)
  172. }
  173. })
  174. this.resultAudioContext.onStop((res) => {
  175. console.log('109-resultAudioContext.onStop');
  176. this.setData({
  177. exampleState: false
  178. })
  179. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  180. this.videoContext.stop()
  181. this.videoContext.seek(0)
  182. }
  183. });
  184. this.resultAudioContext.onEnded(res => {
  185. this.setData({
  186. ["silderData.sliderValue"]: 100
  187. })
  188. })
  189. },
  190. onShow() {
  191. this.getVipInfo()
  192. },
  193. // 获取是否vip
  194. async getVipInfo() {
  195. let isVip = await getVipInfo()
  196. console.log(isVip, '111');
  197. this.setData({
  198. isVip
  199. })
  200. },
  201. // 获取阅读内容
  202. getreadInfo(videoId, reset = false) {
  203. return new Promise(async (resolve, reject) => {
  204. let videoInfo = await getreadInfo(videoId)
  205. let data = JSON.parse(videoInfo.userReadExtend.lessonText)
  206. data = data.map((item, index) => {
  207. item.time = Number(item.time)
  208. item.readTime = data[index + 1] ? data[index + 1].time - item.time : ''
  209. return item
  210. })
  211. this.setData({
  212. videoPath: videoInfo.userRead.originVideo,
  213. article: data,
  214. videoInfo,
  215. ["silderData.endTime"]: setDuration(videoInfo.userRead.duration)
  216. })
  217. if (!reset) {
  218. this.getHeight()
  219. }
  220. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  221. this.videoContext = wx.createVideoContext('myVideo')
  222. } else {
  223. this.innerAudioContext.src = videoInfo.userRead.originVideo
  224. this.innerAudioContext.onEnded(res => {
  225. console.log("138innerAudioContext触发的");
  226. this.resetReading()
  227. })
  228. this.innerAudioContext.onStop((res) => {
  229. console.log("143innerAudioContext触发的");
  230. });
  231. }
  232. resolve()
  233. })
  234. },
  235. // 开始录制
  236. setCountDown() {
  237. if (!this.data.isVip) {
  238. this.resetReading()
  239. return this.selectComponent('#buyVip').open({
  240. vipTime: this.data.isVip
  241. })
  242. }
  243. /* let child = this.selectComponent('#readingTips').data
  244. // 判断是否有权限朗读 不是vip并且没有朗读机会
  245. const isVip = child.vipTime ? true : false
  246. if (!isVip && child.userInfo.experienceAmount <= 0) {
  247. return this.selectComponent('#readingTips').showModal();
  248. } */
  249. if (this.data.state) {
  250. this.resetReading()
  251. return
  252. }
  253. if (!this.data.readingReset) {
  254. this.getHeight()
  255. }
  256. this.resetReading()
  257. this.setData({
  258. readingReset: false,
  259. 'countDown.state': true
  260. })
  261. this.stl = setInterval(async () => {
  262. if (this.data.countDown.num == 0) {
  263. clearInterval(this.stl)
  264. this.setData({
  265. state: true,
  266. countDown: {
  267. state: false,
  268. num: 3
  269. }
  270. })
  271. await this.playMediaState()
  272. await this.soundRecording()
  273. this.startRecording()
  274. } else {
  275. this.setData({
  276. 'countDown.num': --this.data.countDown.num
  277. })
  278. }
  279. }, 1000)
  280. },
  281. // 录音
  282. soundRecording() {
  283. /*调用微信开始录音接口,并启动语音评测*/
  284. let timeStamp = new Date().getTime()
  285. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  286. let app = {
  287. applicationId: '16075689600000da',
  288. sig, //签名字符串
  289. alg: 'sha1',
  290. timestamp: timeStamp + '',
  291. userId: wx.getStorageSync('uid')
  292. }
  293. let lessonText = JSON.parse(this.data.videoInfo.userReadExtend.lessonText).map((item) => {
  294. return item.text
  295. }).join('')
  296. // https://www.chivox.com/opendoc/#/ChineseDoc/coreCn/Chinese/cn.sent.raw?id=%e5%8f%82%e6%95%b0%e8%af%b4%e6%98%8e <----参数说明
  297. wsEngine.start({
  298. request: {
  299. coreType: "cn.pred.raw",
  300. refText: lessonText,
  301. rank: 100,
  302. attachAudioUrl: 1,
  303. result: {
  304. details: {
  305. gop_adjust: -0.1 //评测系数
  306. }
  307. }
  308. },
  309. app,
  310. audio: {
  311. audioType: "mp3",
  312. channel: 1,
  313. sampleBytes: 2,
  314. sampleRate: 16000
  315. },
  316. success: (res) => {
  317. /*引擎启动成功,可以启动录音机开始录音,并将音频片传给引擎*/
  318. const options = {
  319. duration: 600000,
  320. sampleRate: 44100, //采样率
  321. numberOfChannels: 1, //录音通道数
  322. encodeBitRate: 192000, //编码码率
  323. format: 'mp3', //音频格式,有效值aac/mp3
  324. frameSize: 50 //指定帧大小,单位 KB
  325. };
  326. //开始录音,在开始录音回调中feed音频片
  327. recorderManager.start(options);
  328. },
  329. fail: (res) => {
  330. console.log("fail============= ", res);
  331. },
  332. });
  333. recorderManager.onError(res => {
  334. console.log(res, 'rrrrrsse');
  335. })
  336. //监听录音开始事件
  337. recorderManager.onStart(() => {});
  338. //监听录音结束事件
  339. recorderManager.onStop((res) => {
  340. console.log('录音结束', res);
  341. this.setData({
  342. tempFilePath: res.tempFilePath,
  343. });
  344. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  345. wsEngine.stop({
  346. success: () => {
  347. console.log('====== wsEngine stop success ======');
  348. },
  349. fail: (res) => {
  350. console.log('录音结束报错', res);
  351. },
  352. });
  353. });
  354. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  355. recorderManager.onFrameRecorded((res) => {
  356. const {
  357. frameBuffer
  358. } = res
  359. //TODO 调用feed接口传递音频片给驰声评测引擎
  360. wsEngine.feed({
  361. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  362. success: () => {},
  363. fail: (res) => {
  364. console.log('监听已录制完指定帧大小报错', res)
  365. },
  366. });
  367. });
  368. },
  369. // 直接跳转的时候用的,勿动
  370. // util() {
  371. // wx.navigateTo({
  372. // url: `/pages/score/index?readingType=${this.data.readingType}`,
  373. // events: {
  374. // // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
  375. // someEvent: (data) => {
  376. // console.log(data)
  377. // this.setData({
  378. // readingReset: data.reset || false,
  379. // readingType: data.readingType || 'public',
  380. // uploadHide: data.uploadHide
  381. // })
  382. // console.log(this.data, 'ggggggggg');
  383. // }
  384. // },
  385. // })
  386. // },
  387. // 获取测评结果
  388. async getRecordScore(res) {
  389. const result = res.result;
  390. const integrity = Math.floor(result.integrity); //完成度
  391. const tone = Math.floor(result.tone); // 语调声调
  392. const accuracy = Math.floor(result.accuracy); // 准确度 发音分
  393. const fluency = Math.floor(result.fluency.overall); //流利度
  394. let myOverall = Math.floor(integrity * 0.45 + accuracy * 0.35 + fluency * 0.1 + tone * 0.1);
  395. let detail = {
  396. integrity,
  397. tone,
  398. accuracy,
  399. fluency,
  400. myOverall,
  401. tempFilePath: this.data.tempFilePath,
  402. title: this.data.videoInfo.userRead.title,
  403. id: this.data.videoInfo.userRead.exampleId,
  404. coverImg: this.data.videoInfo.userRead.coverImg,
  405. resourcesType: this.data.videoInfo.userReadExtend.resourcesType,
  406. aBg: this.data.videoInfo.userReadExtend.resourcesType == 1 ? this.data.videoInfo.userReadExtend.backgroundVirtualImg : '',
  407. originVideo: this.data.videoInfo.userRead.originVideo
  408. }
  409. console.log('评测结果', detail);
  410. this.setReadDetail(detail)
  411. await userEvent({
  412. action: 'WXSCORE',
  413. })
  414. if (this.data.readingType == 'public' || this.data.readingType == 'readMatch') {
  415. wx.navigateTo({
  416. url: `/pages/score/index?readingType=${this.data.readingType}&activityId=${this.data.activityId}`,
  417. events: {
  418. // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
  419. goback: (data) => {
  420. this.setData({
  421. readingReset: data.reset || false,
  422. readingType: data.readingType || 'public',
  423. uploadHide: data.uploadHide
  424. })
  425. }
  426. },
  427. })
  428. } else {
  429. this.uploadAudio()
  430. }
  431. },
  432. // 挑战录音上传
  433. uploadAudio() {
  434. this.setData({
  435. uploadState: true
  436. })
  437. const uploadTask = wx.uploadFile({
  438. url: 'https://reader-api.ai160.com//file/upload',
  439. filePath: this.data.tempFilePath,
  440. name: '朗读录音',
  441. header: {
  442. uid: wx.getStorageSync('uid')
  443. },
  444. success: async (res) => {
  445. const formateRes = JSON.parse(res.data);
  446. let audioPath = formateRes.data;
  447. let uploadRes = await publishWorks({
  448. exampleId: this.data.pkData.exampleId,
  449. audioPath,
  450. })
  451. let _data = this.data.readDetail
  452. let scoreRes = await postWorksScore({
  453. "userReadId": uploadRes.id,
  454. "complete": _data.integrity,
  455. "accuracy": _data.accuracy,
  456. "speed": _data.fluency,
  457. "intonation": _data.tone,
  458. "score": _data.myOverall
  459. }).finally(() => {
  460. this.setData({
  461. uploadState: false
  462. })
  463. })
  464. console.log({
  465. "userReadId": uploadRes.id,
  466. "complete": _data.integrity,
  467. "accuracy": _data.accuracy,
  468. "speed": _data.fluency,
  469. "intonation": _data.tone,
  470. "score": _data.myOverall
  471. }, 'score', scoreRes, 'scoreRes');
  472. let data = {
  473. challengerUserReadId: uploadRes.id,
  474. userReadId: this.data.pkData.id,
  475. winnerUId: this.data.pkData.score > _data.myOverall ? this.data.pkData.uid : this.data.pkData.score == _data.myOverall ? '' : wx.getStorageSync('uid')
  476. }
  477. console.log('data----', this.data.pkData.score, _data.myOverall, data);
  478. let result = await uploadPk(data)
  479. await userEvent({
  480. action: 'WXPKUPLOAD',
  481. })
  482. wx.redirectTo({
  483. url: `/pages/pkResult/index?id=${result.id}`
  484. })
  485. },
  486. fail: (res) => {
  487. this.setData({
  488. uploadState: false
  489. })
  490. }
  491. });
  492. uploadTask.onProgressUpdate((res) => {
  493. console.log('作品上传进度', res.progress);
  494. this.setData({
  495. percent: res.progress
  496. })
  497. })
  498. },
  499. // 字体换行
  500. startRecording() {
  501. setTimeout(() => {
  502. if (this.data.currentRow == null) {
  503. this.setData({
  504. currentRow: 0
  505. })
  506. }
  507. let row = this.data.article[this.data.currentRow]
  508. if (!row.readTime) {
  509. return
  510. }
  511. this.setTimeoutObj = setTimeout(() => {
  512. this.setData({
  513. currentRow: ++this.data.currentRow
  514. })
  515. this.setData({
  516. scrollTop: this.rowH * this.data.currentRow
  517. })
  518. this.startRecording()
  519. },
  520. row.readTime);
  521. }, 100)
  522. },
  523. // 视频播放结束
  524. videoEnd() {
  525. this.resetReading()
  526. },
  527. videoPlay() {
  528. if (this.data.state) {
  529. return
  530. }
  531. if (this.data.videoInfo.userReadExtend.resourcesType == 1) {
  532. if (this.data.exampleState) {
  533. this.setData({
  534. exampleState: false
  535. })
  536. return this.resultAudioContext.stop()
  537. }
  538. this.resultAudioContext.src = this.data.readingReset ? this.data.readDetail.tempFilePath : this.data.videoInfo.userRead.audioPath;
  539. setTimeout(() => {
  540. this.resultAudioContext.play();
  541. }, 200)
  542. this.setData({
  543. exampleState: true
  544. })
  545. } else {
  546. if (this.data.readingReset) {
  547. this.resultAudioContext.src = this.data.readDetail.tempFilePath;
  548. this.resultAudioContext.play();
  549. this.setData({
  550. muted: true,
  551. exampleState: true
  552. })
  553. } else {
  554. this.setData({
  555. muted: false,
  556. exampleState: true
  557. })
  558. }
  559. this.setData({
  560. videoPath: this.data.videoInfo.userRead.videoPath
  561. })
  562. wx.nextTick(() => {
  563. this.videoContext.play()
  564. })
  565. }
  566. this.startRecording()
  567. submitPlayLog({
  568. userReadId: this.data.videoInfo.userRead.exampleId,
  569. playStopTime: 1000
  570. })
  571. },
  572. // 控制视频或音频的播放状态
  573. async playMediaState() {
  574. this.setData({
  575. muted: false
  576. })
  577. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  578. this.setData({
  579. videoPath: this.data.videoInfo.userRead.originVideo
  580. })
  581. wx.nextTick(() => {
  582. this.videoContext.play()
  583. })
  584. } else {
  585. this.innerAudioContext.play();
  586. }
  587. await userEvent({
  588. action: 'WXREADING',
  589. readId: this.data.videoInfo.userRead.id
  590. })
  591. },
  592. // 重置一切状态
  593. resetReading() {
  594. clearTimeout(this.setTimeoutObj)
  595. clearInterval(this.stl)
  596. // 重置视频
  597. if (this.data.videoInfo.userReadExtend.resourcesType == 0) {
  598. this.videoContext.stop()
  599. this.videoContext.seek(0)
  600. }
  601. // 重置试听音频
  602. if (this.data.exampleState) {
  603. this.resultAudioContext.stop()
  604. // 重置录音时的背景音乐
  605. this.innerAudioContext.stop();
  606. console.log('是我暂停了');
  607. }
  608. if (this.data.state) {
  609. // 重置录音时的背景音乐
  610. this.innerAudioContext.stop();
  611. /*微信录音结束*/
  612. recorderManager.stop();
  613. }
  614. this.setData({
  615. exampleState: false,
  616. state: false,
  617. currentRow: null,
  618. scrollTop: 0,
  619. ["silderData.sliderValue"]: 0,
  620. ["silderData.currentTime"]: '00:00'
  621. })
  622. },
  623. // 阻止作品上传时返回
  624. beforeleave() {
  625. this.setData({
  626. uploadState: true
  627. })
  628. },
  629. // 获取设备高度与行高度
  630. getHeight() {
  631. var query = wx.createSelectorQuery();
  632. query.select('.content').boundingClientRect((rect) => {
  633. this.setData({
  634. contentH: rect.height
  635. })
  636. }).exec()
  637. query.select('.row').boundingClientRect((rect) => {
  638. this.rowH = rect.height
  639. }).exec()
  640. },
  641. // 进度条
  642. slider({
  643. detail
  644. }) {
  645. this.resultAudioContext.pause();
  646. this.resultAudioContext.seek(detail.value / 100 * this.data.videoInfo.userRead.duration)
  647. setTimeout(() => {
  648. this.resultAudioContext.play()
  649. }, 300)
  650. },
  651. onHide() {
  652. wsEngine.reset()
  653. this.resetReading()
  654. },
  655. onUnload() {
  656. wsEngine.reset()
  657. this.resetReading()
  658. this.storeBindings.destroyStoreBindings()
  659. },
  660. backReading() {
  661. wx.navigateBack({
  662. delta: 1
  663. })
  664. },
  665. otherWork() {
  666. wx.navigateTo({
  667. url: `/pages/otherWork/index?exampleId=${this.data.videoInfo.userRead.exampleId}`
  668. })
  669. },
  670. async toBuy({
  671. currentTarget
  672. }) {
  673. wx.showLoading({
  674. title: '提交中',
  675. mask: true
  676. })
  677. let res = await buyVip({
  678. productId: currentTarget.dataset.id
  679. }).finally(() => {
  680. wx.hideLoading()
  681. })
  682. let {
  683. timeStamp,
  684. nonceStr,
  685. signType,
  686. paySign
  687. } = res
  688. // package保留字
  689. wx.requestPayment({
  690. timeStamp,
  691. nonceStr,
  692. package: res.package,
  693. signType,
  694. paySign,
  695. success: (res) => {
  696. this.selectComponent('#vipModal').open({
  697. type: 'svip'
  698. })
  699. setTimeout(() => {
  700. this.setUserInfo()
  701. }, 1500)
  702. },
  703. fail(res) {
  704. wx.showToast({
  705. title: "支付失败",
  706. icon: "none",
  707. duration: 3000
  708. })
  709. }
  710. })
  711. },
  712. creatShare() {
  713. return new Promise((resolve, reject) => {
  714. let video = this.data.videoInfo
  715. let context = wx.createSelectorQuery();
  716. context
  717. .select('#share')
  718. .fields({
  719. node: true,
  720. size: true
  721. }).exec((res) => {
  722. const canvas = res[0].node;
  723. const ctx = canvas.getContext('2d');
  724. const dpr = wx.getSystemInfoSync().pixelRatio;
  725. canvas.width = res[0].width * dpr;
  726. canvas.height = res[0].height * dpr;
  727. ctx.scale(dpr, dpr);
  728. ctx.font = '14px PingFang';
  729. let pic = canvas.createImage();
  730. pic.src = video.userReadExtend && video.userReadExtend.resourcesType == 1 ? video.userReadExtend.backgroundVirtualImg : video.userRead.coverImg;
  731. pic.onload = () => {
  732. ctx.drawImage(pic, 0, 0, 375, 211);
  733. let peiyin = canvas.createImage();
  734. peiyin.src = '/static/peiyin.jpg';
  735. peiyin.onload = () => {
  736. ctx.drawImage(peiyin, 0, 211, 375, 89);
  737. //分享
  738. let fx = canvas.createImage();
  739. fx.src = '/static/share.png'
  740. fx.onload = () => {
  741. ctx.drawImage(fx, 12, 220, 20, 20)
  742. ctx.fillText('分享', 36, 238)
  743. // 收藏,一个一个渲染
  744. let sc = canvas.createImage();
  745. sc.src = '/static/no_collect.png'
  746. sc.onload = () => {
  747. ctx.drawImage(sc, 110, 220, 19, 19)
  748. ctx.fillText('收藏', 134, 238)
  749. //点赞
  750. let dz = canvas.createImage();
  751. dz.src = '/static/heart.png'
  752. dz.onload = () => {
  753. ctx.drawImage(dz, 318, 222, 22, 22)
  754. ctx.fillText(0, 254, 238)
  755. // 评论
  756. let pl = canvas.createImage();
  757. pl.src = '/static/comment.png'
  758. pl.onload = () => {
  759. ctx.drawImage(pl, 228, 222, 22, 22)
  760. ctx.fillText(0, 340, 238)
  761. if (video.userReadExtend.resourcesType == 1) {
  762. let aBg = canvas.createImage();
  763. aBg.src = '/static/shareAudioBg.png';
  764. aBg.onload = () => {
  765. ctx.drawImage(aBg, 127.5, 38, 120, 120);
  766. let rate = 0.5
  767. ctx.arc(
  768. Math.floor(375 * rate),
  769. 98,
  770. Math.floor(100 * rate),
  771. 0,
  772. 2 * Math.PI
  773. );
  774. ctx.clip() //裁剪
  775. let coverImg = canvas.createImage();
  776. coverImg.src = video.userRead.coverImg;
  777. coverImg.onload = () => {
  778. ctx.drawImage( //定位在圆圈范围内便会出现
  779. coverImg, //图片暂存路径
  780. 129, 42,
  781. 110, 110,
  782. );
  783. ctx.restore()
  784. }
  785. }
  786. }
  787. setTimeout(() => {
  788. console.log(wx.getStorageSync('shareVideoId'), 'reading-wx.getStorageSync');
  789. wx.canvasToTempFilePath({
  790. canvas: canvas,
  791. success(res) {
  792. resolve({
  793. title: '我的新作品发布啦,快来捧场点赞!',
  794. path: `/pages/pkPage/index?videoId=${wx.getStorageSync('shareVideoId')}&uid=${wx.getStorageSync('uid')}&isShare=true`,
  795. imageUrl: res.tempFilePath
  796. })
  797. },
  798. fail(res) {
  799. reject()
  800. }
  801. }, this)
  802. }, 500)
  803. }
  804. }
  805. }
  806. }
  807. }
  808. }
  809. })
  810. })
  811. },
  812. onShareAppMessage({
  813. from,
  814. target
  815. }) {
  816. if (from == 'button') {
  817. const promise = new Promise(resolve => {
  818. this.creatShare().then(res => {
  819. resolve(res)
  820. })
  821. })
  822. return {
  823. title: '我的新作品发布啦,快来捧场点赞!',
  824. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  825. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg',
  826. promise
  827. }
  828. } else {
  829. return {
  830. title: '自从用了它,家里朗朗书声,美妙极了!你家孩子也快来试试!',
  831. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  832. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg'
  833. }
  834. }
  835. },
  836. })