index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import {
  2. getreadInfo
  3. } from '~/api/video'
  4. import {
  5. publishWorks,
  6. uploadPk
  7. } from '~/api/works'
  8. import {
  9. userEvent
  10. } from '~/api/global'
  11. import {
  12. createStoreBindings
  13. } from 'mobx-miniprogram-bindings'
  14. import {
  15. store
  16. } from '~/store/index'
  17. const aiengine = require('~/utils/ChivoxAiEngine')
  18. const sha1 = require('~/utils/sha1');
  19. // 文章行高
  20. let rowH = 0
  21. let videoContext = null
  22. // 滚动变色定时器
  23. let stl = null
  24. // 倒计时
  25. let setTimeoutObj = null
  26. // 录音
  27. let innerAudioContext = null
  28. let resultAudioContext = null
  29. /*创建基础引擎*/
  30. let wsEngine = aiengine.createWsEngine({});
  31. /*微信录音*/
  32. let recorderManager = wx.getRecorderManager();
  33. Page({
  34. data: {
  35. videoInfo: {},
  36. currentRow: null,
  37. state: false,
  38. countDown: {
  39. state: false,
  40. num: 3,
  41. },
  42. contentH: 0,
  43. scrollTop: 0,
  44. //如果readingReset为true就是重读
  45. readingReset: false,
  46. //readingType为public是普通阅读,为pk是pk逻辑,readMatch为朗读赛
  47. readingType: 'public',
  48. percent: 0,
  49. uploadState: false,
  50. article: []
  51. },
  52. onLoad(options) {
  53. let videoId = options.videoId
  54. this.getreadInfo(videoId, options.reset)
  55. console.log(options, 'options');
  56. this.setData({
  57. readingReset: options.reset || false,
  58. readingType: options.readingType || 'public'
  59. })
  60. // 手工绑定
  61. this.storeBindings = createStoreBindings(this, {
  62. store,
  63. fields: {
  64. userInfo: 'userInfo',
  65. readDetail: 'readDetail',
  66. pkData: 'pkData'
  67. },
  68. actions: {
  69. setReadDetail: 'setReadDetail'
  70. }
  71. })
  72. // 录音授权
  73. wx.getSetting({
  74. success(res) {
  75. if (!res.authSetting['scope.record']) {
  76. wx.authorize({
  77. scope: 'scope.record',
  78. success() {
  79. // 用户已经同意小程序使用录音功能,后续调用接口不会弹窗询问
  80. wx.getRecorderManager()
  81. }
  82. })
  83. }
  84. }
  85. })
  86. /*监听评测结果:必须在基础引擎创建后,调用任何评测接口前设置监听,否则有可能收不到相关事件。*/
  87. wsEngine.onResult((res) => {
  88. this.getRecordScore(res)
  89. });
  90. wsEngine.onErrorResult((res) => {
  91. console.log("===收到错误结果=============", res)
  92. });
  93. },
  94. // 获取阅读内容
  95. async getreadInfo(videoId, reset = false) {
  96. let videoInfo = await getreadInfo(videoId)
  97. wx.setNavigationBarTitle({
  98. title: videoInfo.userRead.title
  99. })
  100. let data = JSON.parse(videoInfo.userReadExtend.lessonText)
  101. data = data.map((item, index) => {
  102. item.time = Number(item.time)
  103. item.readTime = data[index + 1] ? data[index + 1].time - item.time : ''
  104. return item
  105. })
  106. this.setData({
  107. article: data,
  108. videoInfo
  109. })
  110. if (!reset) {
  111. this.getHeight()
  112. }
  113. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  114. this.videoContext = wx.createVideoContext('myVideo')
  115. } else {
  116. this.innerAudioContext = wx.createInnerAudioContext();
  117. this.innerAudioContext.src = videoInfo.userRead.audioPath
  118. this.innerAudioContext.onEnded(res => {
  119. this.finishRecord()
  120. })
  121. this.innerAudioContext.onStop((res) => {
  122. this.finishRecord()
  123. });
  124. }
  125. },
  126. // 开始录制
  127. setCountDown() {
  128. let child = this.selectComponent('#readingTips').data
  129. // 判断是否有权限朗读 不是vip并且没有朗读机会
  130. const isVip = child.vipTime ? true : false
  131. if (!isVip && child.userInfo.experienceAmount == 0) {
  132. return this.selectComponent('#readingTips').showModal();
  133. }
  134. if (this.data.state) {
  135. this.finishRecord()
  136. return
  137. }
  138. if (this.data.readingReset) {
  139. this.clearReset()
  140. this.getHeight()
  141. }
  142. this.setData({
  143. 'countDown.state': true
  144. })
  145. this.stl = setInterval(() => {
  146. if (this.data.countDown.num == 0) {
  147. clearInterval(this.stl)
  148. this.setData({
  149. state: true,
  150. countDown: {
  151. state: false,
  152. num: 3
  153. }
  154. })
  155. this.soundRecording()
  156. this.playMediaState()
  157. this.startRecording()
  158. } else {
  159. this.setData({
  160. 'countDown.num': --this.data.countDown.num
  161. })
  162. }
  163. }, 1000)
  164. },
  165. // 录音
  166. soundRecording() {
  167. /*调用微信开始录音接口,并启动语音评测*/
  168. let timeStamp = new Date().getTime()
  169. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  170. let app = {
  171. applicationId: '16075689600000da',
  172. sig, //签名字符串
  173. alg: 'sha1',
  174. timestamp: timeStamp + '',
  175. userId: wx.getStorageSync('uid')
  176. }
  177. let lessonText = JSON.parse(this.data.videoInfo.userReadExtend.lessonText).map((item) => {
  178. return item.text
  179. }).join('\n')
  180. wsEngine.start({
  181. request: {
  182. coreType: "cn.pred.raw",
  183. refText: lessonText,
  184. rank: 100,
  185. attachAudioUrl: 1,
  186. result: {
  187. details: {
  188. gop_adjust: 1
  189. }
  190. }
  191. },
  192. app,
  193. audio: {
  194. audioType: "mp3",
  195. channel: 1,
  196. sampleBytes: 2,
  197. sampleRate: 16000
  198. },
  199. success: (res) => {
  200. /*引擎启动成功,可以启动录音机开始录音,并将音频片传给引擎*/
  201. const options = {
  202. sampleRate: 44100, //采样率
  203. numberOfChannels: 1, //录音通道数
  204. encodeBitRate: 192000, //编码码率
  205. format: 'mp3', //音频格式,有效值aac/mp3
  206. frameSize: 50 //指定帧大小,单位 KB
  207. };
  208. //开始录音,在开始录音回调中feed音频片
  209. recorderManager.start(options);
  210. },
  211. fail: (res) => {
  212. console.log("fail============= " + res);
  213. },
  214. });
  215. //监听录音开始事件
  216. recorderManager.onStart(() => {});
  217. //监听录音结束事件
  218. recorderManager.onStop((res) => {
  219. console.log('录音结束', res);
  220. this.setData({
  221. tempFilePath: res.tempFilePath,
  222. });
  223. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  224. wsEngine.stop({
  225. success: () => {
  226. console.log('====== wsEngine stop success ======');
  227. },
  228. fail: (res) => {
  229. console.log('录音结束报错', res);
  230. },
  231. });
  232. });
  233. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  234. recorderManager.onFrameRecorded((res) => {
  235. const {
  236. frameBuffer
  237. } = res
  238. //TODO 调用feed接口传递音频片给驰声评测引擎
  239. wsEngine.feed({
  240. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  241. success: () => {
  242. console.log('feed success.监听已录制完指定帧大小的文件事件')
  243. },
  244. fail: (res) => {
  245. console.log('监听已录制完指定帧大小报错', res)
  246. },
  247. });
  248. });
  249. },
  250. // 结束录制
  251. finishRecord() {
  252. recorderManager.stop();
  253. this.stopMediaState()
  254. clearTimeout(this.setTimeoutObj)
  255. clearInterval(this.stl)
  256. this.setData({
  257. state: false,
  258. currentRow: null,
  259. scrollTop: 0
  260. })
  261. },
  262. // 获取测评结果
  263. getRecordScore(res) {
  264. console.log('获取评测结果');
  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. console.log('uploadRes', uploadRes);
  312. /* let winnerUId = this.data.pkData > detail.myOverall ? this.data.pkData.exampleId : this.data.pkData < detail.myOverall ? detail.id : '' */
  313. let data = {
  314. challengerUserReadId: uploadRes.id,
  315. userReadId: this.data.pkData.id,
  316. }
  317. await uploadPk(data)
  318. wx.redirectTo({
  319. url: '/pages/pkResult/index'
  320. })
  321. },
  322. complete: () => {
  323. this.setData({
  324. uploadState: false
  325. })
  326. }
  327. });
  328. uploadTask.onProgressUpdate((res) => {
  329. this.setData({
  330. percent: res.progress
  331. })
  332. })
  333. },
  334. // 测试的
  335. pkResult() {
  336. wx.redirectTo({
  337. url: `/pages/score/index?readingType=${this.data.readingType}`
  338. })
  339. /* wx.redirectTo({
  340. url: `/pages/pkResult/index`,
  341. }) */
  342. },
  343. // 字体换行
  344. startRecording() {
  345. if (this.data.currentRow == null) {
  346. this.setData({
  347. currentRow: 0
  348. })
  349. }
  350. let row = this.data.article[this.data.currentRow]
  351. if (!row.readTime) {
  352. return
  353. }
  354. this.setTimeoutObj = setTimeout(() => {
  355. this.setData({
  356. currentRow: ++this.data.currentRow
  357. })
  358. this.setData({
  359. scrollTop: this.rowH * this.data.currentRow
  360. })
  361. this.startRecording()
  362. },
  363. row.readTime);
  364. },
  365. // 视频播放结束
  366. videoEnd() {
  367. this.finishRecord()
  368. },
  369. videoPlay() {
  370. if (this.data.readingReset) {
  371. this.resultAudioContext = wx.createInnerAudioContext();
  372. this.resultAudioContext.src = this.data.readDetail.tempFilePath; // 这里可以是录音的临时路径
  373. this.resultAudioContext.play();
  374. }
  375. },
  376. // 清除试听状态
  377. clearReset() {
  378. if (this.resultAudioContext) {
  379. this.resultAudioContext.stop()
  380. }
  381. this.setData({
  382. readingReset: false
  383. })
  384. },
  385. // 控制视频或音频的播放状态
  386. async playMediaState() {
  387. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  388. this.videoContext.play()
  389. } else {
  390. this.innerAudioContext.play();
  391. }
  392. await userEvent({
  393. action: 'READING',
  394. readId:this.data.videoInfo.userRead.id
  395. })
  396. },
  397. // 控制视频或音频的暂停状态
  398. stopMediaState() {
  399. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  400. this.videoContext.stop()
  401. this.videoContext.seek(0)
  402. } else {
  403. this.innerAudioContext.stop()
  404. }
  405. },
  406. // 获取设备高度与行高度
  407. getHeight() {
  408. var query = wx.createSelectorQuery();
  409. query.select('.content').boundingClientRect((rect) => {
  410. this.setData({
  411. contentH: rect.height
  412. })
  413. }).exec()
  414. query.select('.row').boundingClientRect((rect) => {
  415. this.rowH = rect.height
  416. }).exec()
  417. },
  418. /**
  419. * 生命周期函数--监听页面卸载
  420. */
  421. onUnload() {
  422. wsEngine.reset()
  423. recorderManager.stop();
  424. if (this.innerAudioContext) {
  425. this.innerAudioContext.stop()
  426. }
  427. clearTimeout(this.setTimeoutObj)
  428. clearInterval(this.stl)
  429. },
  430. })