index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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
  98. console.log(videoInfo);
  99. if (videoInfo.userReadExtend) {
  100. 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. } else {
  107. data = videoInfo.userRead.lessonText.split('\n'),
  108. console.log(data);
  109. }
  110. this.setData({
  111. article: data,
  112. videoInfo
  113. })
  114. if (!reset) {
  115. this.getHeight()
  116. }
  117. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  118. this.videoContext = wx.createVideoContext('myVideo')
  119. } else {
  120. this.innerAudioContext = wx.createInnerAudioContext();
  121. this.innerAudioContext.src = videoInfo.userRead.audioPath
  122. this.innerAudioContext.onEnded(res => {
  123. this.finishRecord()
  124. })
  125. this.innerAudioContext.onStop((res) => {
  126. this.finishRecord()
  127. });
  128. }
  129. },
  130. // 开始录制
  131. setCountDown() {
  132. let child = this.selectComponent('#readingTips').data
  133. // 判断是否有权限朗读 不是vip并且没有朗读机会
  134. const isVip = child.vipTime ? true : false
  135. if (!isVip && child.userInfo.experienceAmount == 0) {
  136. return this.selectComponent('#readingTips').showModal();
  137. }
  138. if (this.data.state) {
  139. this.finishRecord()
  140. return
  141. }
  142. if (this.data.readingReset) {
  143. this.clearReset()
  144. this.getHeight()
  145. }
  146. this.setData({
  147. 'countDown.state': true
  148. })
  149. this.stl = setInterval(() => {
  150. if (this.data.countDown.num == 0) {
  151. clearInterval(this.stl)
  152. this.setData({
  153. state: true,
  154. countDown: {
  155. state: false,
  156. num: 3
  157. }
  158. })
  159. this.soundRecording()
  160. this.playMediaState()
  161. this.startRecording()
  162. } else {
  163. this.setData({
  164. 'countDown.num': --this.data.countDown.num
  165. })
  166. }
  167. }, 1000)
  168. },
  169. // 录音
  170. soundRecording() {
  171. /*调用微信开始录音接口,并启动语音评测*/
  172. let timeStamp = new Date().getTime()
  173. let sig = sha1(`16075689600000da${timeStamp}caa8e60da6042731c230fe431ac9c7fd`)
  174. let app = {
  175. applicationId: '16075689600000da',
  176. sig, //签名字符串
  177. alg: 'sha1',
  178. timestamp: timeStamp + '',
  179. userId: wx.getStorageSync('uid')
  180. }
  181. let lessonText = this.data.videoInfo.userRead.lessonText;
  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. console.log('feed success.监听已录制完指定帧大小的文件事件')
  245. },
  246. fail: (res) => {
  247. console.log('监听已录制完指定帧大小报错', res)
  248. },
  249. });
  250. });
  251. },
  252. // 结束录制
  253. finishRecord() {
  254. recorderManager.stop();
  255. this.stopMediaState()
  256. clearTimeout(this.setTimeoutObj)
  257. clearInterval(this.stl)
  258. this.setData({
  259. state: false,
  260. currentRow: null,
  261. scrollTop: 0
  262. })
  263. },
  264. // 获取测评结果
  265. getRecordScore(res) {
  266. console.log('获取评测结果');
  267. const result = res.result;
  268. const integrity = Math.floor(result.integrity); //完成度
  269. const tone = Math.floor(result.tone); // 语调声调
  270. const accuracy = Math.floor(result.overall); // 准确度 发音分
  271. const fluency = Math.floor(result.fluency.overall); //流利度
  272. let myOverall = Math.floor(integrity * 0.3 + accuracy * 0.5 + fluency * 0.1 + tone * 0.1);
  273. let detail = {
  274. integrity,
  275. tone,
  276. accuracy,
  277. fluency,
  278. myOverall,
  279. tempFilePath: this.data.tempFilePath,
  280. title: this.data.videoInfo.userRead.title,
  281. id: this.data.videoInfo.userRead.exampleId,
  282. coverImg: this.data.videoInfo.userRead.coverImg,
  283. originVideo: this.data.videoInfo.userRead.originVideo
  284. }
  285. this.setReadDetail(detail)
  286. if (this.data.readingType == 'public' || this.data.readingType == 'readMatch') {
  287. wx.redirectTo({
  288. url: `/pages/score/index?readingType=${this.data.readingType}`
  289. })
  290. } else {
  291. this.uploadAudio(detail)
  292. }
  293. },
  294. // 挑战录音上传
  295. uploadAudio(detail) {
  296. this.setData({
  297. uploadState: true
  298. })
  299. const uploadTask = wx.uploadFile({
  300. url: 'https://reader-api.ai160.com//file/upload',
  301. filePath: this.data.tempFilePath,
  302. name: '朗读录音',
  303. header: {
  304. uid: wx.getStorageSync('uid')
  305. },
  306. success: async (res) => {
  307. const formateRes = JSON.parse(res.data);
  308. let audioPath = formateRes.data;
  309. let uploadRes = await publishWorks({
  310. exampleId: this.data.pkData.exampleId,
  311. audioPath
  312. })
  313. console.log('uploadRes', uploadRes);
  314. /* let winnerUId = this.data.pkData > detail.myOverall ? this.data.pkData.exampleId : this.data.pkData < detail.myOverall ? detail.id : '' */
  315. let data = {
  316. challengerUserReadId: uploadRes.id,
  317. userReadId: this.data.pkData.id,
  318. }
  319. await uploadPk(data)
  320. wx.redirectTo({
  321. url: '/pages/pkResult/index'
  322. })
  323. },
  324. complete: () => {
  325. this.setData({
  326. uploadState: false
  327. })
  328. }
  329. });
  330. uploadTask.onProgressUpdate((res) => {
  331. this.setData({
  332. percent: res.progress
  333. })
  334. })
  335. },
  336. // 测试的
  337. pkResult() {
  338. wx.redirectTo({
  339. url: `/pages/score/index?readingType=${this.data.readingType}`
  340. })
  341. /* wx.redirectTo({
  342. url: `/pages/pkResult/index`,
  343. }) */
  344. },
  345. // 字体换行
  346. startRecording() {
  347. if (this.data.currentRow == null) {
  348. this.setData({
  349. currentRow: 0
  350. })
  351. }
  352. let row = this.data.article[this.data.currentRow]
  353. if (!row.readTime) {
  354. return
  355. }
  356. this.setTimeoutObj = setTimeout(() => {
  357. this.setData({
  358. currentRow: ++this.data.currentRow
  359. })
  360. this.setData({
  361. scrollTop: this.rowH * this.data.currentRow
  362. })
  363. this.startRecording()
  364. },
  365. row.readTime);
  366. },
  367. // 视频播放结束
  368. videoEnd() {
  369. this.finishRecord()
  370. },
  371. videoPlay() {
  372. if (this.data.readingReset) {
  373. this.resultAudioContext = wx.createInnerAudioContext();
  374. this.resultAudioContext.src = this.data.readDetail.tempFilePath; // 这里可以是录音的临时路径
  375. this.resultAudioContext.play();
  376. }
  377. },
  378. // 清除试听状态
  379. clearReset() {
  380. if (this.resultAudioContext) {
  381. this.resultAudioContext.stop()
  382. }
  383. this.setData({
  384. readingReset: false
  385. })
  386. },
  387. // 控制视频或音频的播放状态
  388. playMediaState() {
  389. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  390. this.videoContext.play()
  391. } else {
  392. this.innerAudioContext.play();
  393. }
  394. },
  395. // 控制视频或音频的暂停状态
  396. stopMediaState() {
  397. if (!this.data.videoInfo.userReadExtend || this.data.videoInfo.userReadExtend.resourcesType == 0) {
  398. this.videoContext.stop()
  399. this.videoContext.seek(0)
  400. } else {
  401. this.innerAudioContext.stop()
  402. }
  403. },
  404. // 获取设备高度与行高度
  405. getHeight() {
  406. var query = wx.createSelectorQuery();
  407. query.select('.content').boundingClientRect((rect) => {
  408. this.setData({
  409. contentH: rect.height
  410. })
  411. }).exec()
  412. query.select('.row').boundingClientRect((rect) => {
  413. this.rowH = rect.height
  414. }).exec()
  415. },
  416. /**
  417. * 生命周期函数--监听页面卸载
  418. */
  419. onUnload() {
  420. wsEngine.reset()
  421. recorderManager.stop();
  422. if (this.innerAudioContext) {
  423. this.innerAudioContext.stop()
  424. }
  425. clearTimeout(this.setTimeoutObj)
  426. clearInterval(this.stl)
  427. },
  428. })