index.js 35 KB

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