index.js 12 KB

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