index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. let child = this.selectComponent('#readingTips').data
  130. // 判断是否有权限朗读 不是vip并且没有朗读机会
  131. const isVip = child.vipTime ? true : false
  132. if (!isVip && child.userInfo.experienceAmount == 0) {
  133. return this.selectComponent('#readingTips').showModal();
  134. }
  135. if (this.data.state) {
  136. this.finishRecord()
  137. return
  138. }
  139. if (this.data.readingReset) {
  140. this.clearReset()
  141. this.getHeight()
  142. }
  143. this.setData({
  144. 'countDown.state': true
  145. })
  146. this.stl = setInterval(() => {
  147. if (this.data.countDown.num == 0) {
  148. clearInterval(this.stl)
  149. this.setData({
  150. state: true,
  151. countDown: {
  152. state: false,
  153. num: 3
  154. }
  155. })
  156. this.soundRecording()
  157. this.playMediaState()
  158. this.startRecording()
  159. } else {
  160. this.setData({
  161. 'countDown.num': --this.data.countDown.num
  162. })
  163. }
  164. }, 1000)
  165. },
  166. // 录音
  167. soundRecording() {
  168. /*调用微信开始录音接口,并启动语音评测*/
  169. let timeStamp = new Date().getTime()
  170. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  171. let app = {
  172. applicationId: '16075689600000da',
  173. sig, //签名字符串
  174. alg: 'sha1',
  175. timestamp: timeStamp + '',
  176. userId: wx.getStorageSync('uid')
  177. }
  178. let lessonText = JSON.parse(this.data.videoInfo.userReadExtend.lessonText).map((item) => {
  179. return item.text
  180. }).join('\n')
  181. wsEngine.start({
  182. request: {
  183. coreType: "cn.pred.raw",
  184. refText: lessonText,
  185. rank: 100,
  186. attachAudioUrl: 1,
  187. result: {
  188. details: {
  189. gop_adjust: 1
  190. }
  191. }
  192. },
  193. app,
  194. audio: {
  195. audioType: "mp3",
  196. channel: 1,
  197. sampleBytes: 2,
  198. sampleRate: 16000
  199. },
  200. success: (res) => {
  201. /*引擎启动成功,可以启动录音机开始录音,并将音频片传给引擎*/
  202. const options = {
  203. sampleRate: 44100, //采样率
  204. numberOfChannels: 1, //录音通道数
  205. encodeBitRate: 192000, //编码码率
  206. format: 'mp3', //音频格式,有效值aac/mp3
  207. frameSize: 50 //指定帧大小,单位 KB
  208. };
  209. //开始录音,在开始录音回调中feed音频片
  210. recorderManager.start(options);
  211. },
  212. fail: (res) => {
  213. console.log("fail============= " + res);
  214. },
  215. });
  216. //监听录音开始事件
  217. recorderManager.onStart(() => {});
  218. //监听录音结束事件
  219. recorderManager.onStop((res) => {
  220. console.log('录音结束', res);
  221. this.setData({
  222. tempFilePath: res.tempFilePath,
  223. });
  224. //录音机结束后,驰声引擎执行结束操作,等待评测返回结果
  225. wsEngine.stop({
  226. success: () => {
  227. console.log('====== wsEngine stop success ======');
  228. },
  229. fail: (res) => {
  230. console.log('录音结束报错', res);
  231. },
  232. });
  233. });
  234. //监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
  235. recorderManager.onFrameRecorded((res) => {
  236. const {
  237. frameBuffer
  238. } = res
  239. //TODO 调用feed接口传递音频片给驰声评测引擎
  240. wsEngine.feed({
  241. data: frameBuffer, // frameBuffer为微信录音机回调的音频数据
  242. success: () => {},
  243. fail: (res) => {
  244. console.log('监听已录制完指定帧大小报错', res)
  245. },
  246. });
  247. });
  248. },
  249. // 结束录制
  250. finishRecord() {
  251. recorderManager.stop();
  252. this.stopMediaState()
  253. clearTimeout(this.setTimeoutObj)
  254. clearInterval(this.stl)
  255. this.setData({
  256. state: false,
  257. currentRow: null,
  258. scrollTop: 0
  259. })
  260. },
  261. // 获取测评结果
  262. getRecordScore(res) {
  263. const result = res.result;
  264. const integrity = Math.floor(result.integrity); //完成度
  265. const tone = Math.floor(result.tone); // 语调声调
  266. const accuracy = Math.floor(result.overall); // 准确度 发音分
  267. const fluency = Math.floor(result.fluency.overall); //流利度
  268. let myOverall = Math.floor(integrity * 0.3 + accuracy * 0.5 + fluency * 0.1 + tone * 0.1);
  269. let detail = {
  270. integrity,
  271. tone,
  272. accuracy,
  273. fluency,
  274. myOverall,
  275. tempFilePath: this.data.tempFilePath,
  276. title: this.data.videoInfo.userRead.title,
  277. id: this.data.videoInfo.userRead.exampleId,
  278. coverImg: this.data.videoInfo.userRead.coverImg,
  279. originVideo: this.data.videoInfo.userRead.originVideo
  280. }
  281. this.setReadDetail(detail)
  282. if (this.data.readingType == 'public' || this.data.readingType == 'readMatch') {
  283. wx.redirectTo({
  284. url: `/pages/score/index?readingType=${this.data.readingType}`
  285. })
  286. } else {
  287. this.uploadAudio(detail)
  288. }
  289. },
  290. // 挑战录音上传
  291. uploadAudio(detail) {
  292. this.setData({
  293. uploadState: true
  294. })
  295. const uploadTask = wx.uploadFile({
  296. url: 'https://reader-api.ai160.com//file/upload',
  297. filePath: this.data.tempFilePath,
  298. name: '朗读录音',
  299. header: {
  300. uid: wx.getStorageSync('uid')
  301. },
  302. success: async (res) => {
  303. const formateRes = JSON.parse(res.data);
  304. let audioPath = formateRes.data;
  305. let uploadRes = await publishWorks({
  306. exampleId: this.data.pkData.exampleId,
  307. audioPath
  308. })
  309. let _data = this.data.readDetail
  310. postWorksScore({
  311. "userReadId": uploadRes.id,
  312. "complete": _data.integrity,
  313. "accuracy": _data.accuracy,
  314. "speed": _data.fluency,
  315. "intonation": _data.tone,
  316. "score": _data.myOverall
  317. })
  318. let data = {
  319. challengerUserReadId: uploadRes.id,
  320. userReadId: this.data.pkData.id,
  321. }
  322. let result = await uploadPk(data)
  323. console.log(result, 'pk结果');
  324. wx.redirectTo({
  325. url: '/pages/pkResult/index'
  326. })
  327. },
  328. complete: () => {
  329. this.setData({
  330. uploadState: false
  331. })
  332. }
  333. });
  334. uploadTask.onProgressUpdate((res) => {
  335. this.setData({
  336. percent: res.progress
  337. })
  338. })
  339. },
  340. // 测试的
  341. pkResult() {
  342. wx.redirectTo({
  343. url: `/pages/score/index?readingType=${this.data.readingType}`
  344. })
  345. /* wx.redirectTo({
  346. url: `/pages/pkResult/index`,
  347. }) */
  348. },
  349. // 字体换行
  350. startRecording() {
  351. if (this.data.currentRow == null) {
  352. this.setData({
  353. currentRow: 0
  354. })
  355. }
  356. let row = this.data.article[this.data.currentRow]
  357. if (!row.readTime) {
  358. return
  359. }
  360. this.setTimeoutObj = setTimeout(() => {
  361. this.setData({
  362. currentRow: ++this.data.currentRow
  363. })
  364. this.setData({
  365. scrollTop: this.rowH * this.data.currentRow
  366. })
  367. this.startRecording()
  368. },
  369. row.readTime);
  370. },
  371. // 视频播放结束
  372. videoEnd() {
  373. this.finishRecord()
  374. },
  375. videoPlay() {
  376. if (this.data.readingReset) {
  377. this.resultAudioContext = wx.createInnerAudioContext();
  378. this.resultAudioContext.src = this.data.readDetail.tempFilePath; // 这里可以是录音的临时路径
  379. this.resultAudioContext.play();
  380. }
  381. },
  382. // 清除试听状态
  383. clearReset() {
  384. if (this.resultAudioContext) {
  385. this.resultAudioContext.stop()
  386. }
  387. this.setData({
  388. readingReset: false
  389. })
  390. },
  391. // 控制视频或音频的播放状态
  392. async playMediaState() {
  393. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  394. this.videoContext.play()
  395. } else {
  396. this.innerAudioContext.play();
  397. }
  398. await userEvent({
  399. action: 'READING',
  400. readId: this.data.videoInfo.userRead.id
  401. })
  402. },
  403. // 控制视频或音频的暂停状态
  404. stopMediaState() {
  405. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  406. this.videoContext.stop()
  407. this.videoContext.seek(0)
  408. } else {
  409. this.innerAudioContext.stop()
  410. }
  411. },
  412. // 获取设备高度与行高度
  413. getHeight() {
  414. var query = wx.createSelectorQuery();
  415. query.select('.content').boundingClientRect((rect) => {
  416. this.setData({
  417. contentH: rect.height
  418. })
  419. }).exec()
  420. query.select('.row').boundingClientRect((rect) => {
  421. this.rowH = rect.height
  422. }).exec()
  423. },
  424. /**
  425. * 生命周期函数--监听页面卸载
  426. */
  427. onUnload() {
  428. wsEngine.reset()
  429. recorderManager.stop();
  430. if (this.innerAudioContext) {
  431. this.innerAudioContext.stop()
  432. }
  433. clearTimeout(this.setTimeoutObj)
  434. clearInterval(this.stl)
  435. },
  436. })