index.js 12 KB

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