index.js 14 KB

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