index.js 35 KB

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