index.js 12 KB

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