index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import {
  2. getActivityInfo,
  3. getShareText,
  4. saveActivity
  5. } from '~/api/activity'
  6. import {
  7. actionRecord
  8. } from '~/api/global'
  9. /*微信录音*/
  10. let recorderManager = wx.getRecorderManager();
  11. let dsq
  12. Page({
  13. /**
  14. * 页面的初始数据
  15. */
  16. data: {
  17. // 'before录制前, process 录制中,after录制后'
  18. state: 'before',
  19. tens: 3,
  20. bits: 0,
  21. configure: {},
  22. avatar: '',
  23. // 本地录音地址
  24. tempFilePath: '',
  25. // 线上录音地址
  26. audioPath: '',
  27. uploadState: false,
  28. focusTo: false,
  29. focusFrom: false,
  30. // 此id保存模板使用
  31. id: '',
  32. greeting: [],
  33. greetingCard: null,
  34. userAudioState: false,
  35. // 当前音频播放时长
  36. playTime: '00:00',
  37. endTime: '00:00',
  38. vProgress: 0
  39. },
  40. async onLoad(options) {
  41. let configure = await getActivityInfo(options.id)
  42. wx.setNavigationBarTitle({
  43. title: configure.title,
  44. })
  45. this.setData({
  46. configure,
  47. avatar: configure.photoText,
  48. id: options.id,
  49. greeting: configure.greeting.split('\n'),
  50. tens: configure.bgMusicLength[0],
  51. bits: configure.bgMusicLength[1]
  52. })
  53. this.innerAudioContext = wx.createInnerAudioContext();
  54. this.innerAudioContext.src = configure.bgMusic; // 这里可以是录音的临时路径
  55. // 录音授权
  56. wx.getSetting({
  57. success(res) {
  58. console.log(res);
  59. if (!res.authSetting['scope.record']) {
  60. wx.authorize({
  61. scope: 'scope.record',
  62. success() {
  63. // 用户已经同意小程序使用录音功能,后续调用接口不会弹窗询问
  64. }
  65. })
  66. }
  67. }
  68. })
  69. await actionRecord({
  70. action: 'NEW_YEAR_ACTIVITY_CHOOSE_TEMPLATE',
  71. targetContent: options.id
  72. })
  73. },
  74. showActionSheet() {
  75. wx.chooseMedia({
  76. count: 1,
  77. mediaType: ['image'],
  78. sizeType: ['compressed'], // 必须放在 数组里面才有效; original 原图;compressed 压缩图
  79. sourceType: ['album', 'camera'],
  80. camera: 'back',
  81. success: (res) => {
  82. this.cropper = this.selectComponent("#yeyouzi-cropper");
  83. this.cropper.init({
  84. imgPath: res.tempFiles[0].tempFilePath, //imgPath是需要裁剪图片的图片路径,只支持本地或临时路径
  85. success: (res) => {
  86. this.changeAvatar(res)
  87. },
  88. fail(error) {
  89. console.log(error) //有两种:cancel代表点击了叉,fail代表wx.canvasToTempFilePath生成图片失败
  90. }
  91. });
  92. }
  93. })
  94. },
  95. async changeAvatar(e) {
  96. let res = await this.uploadFile(e)
  97. this.setData({
  98. avatar: res
  99. })
  100. },
  101. play() {
  102. if (this.data.state == 'before') {
  103. this.innerAudioContext.play();
  104. this.innerAudioContext.onEnded((res) => {
  105. console.log('音频播放完毕');
  106. this.setData({
  107. userAudioState: false
  108. })
  109. });
  110. this.setData({
  111. state: 'process'
  112. })
  113. let countDown = Number(this.data.configure.bgMusicLength)
  114. // 倒计时
  115. this.dsq = setInterval(item => {
  116. console.log('仍然倒计时呢');
  117. // 倒计时结束
  118. if (countDown == 1) {
  119. this.stopRecording()
  120. }
  121. if (countDown % 10 == 0) {
  122. this.setData({
  123. tens: --this.data.tens,
  124. bits: 9
  125. })
  126. } else {
  127. this.setData({
  128. bits: --this.data.bits
  129. })
  130. }
  131. --countDown
  132. }, 1000)
  133. const options = {
  134. sampleRate: 44100, //采样率
  135. numberOfChannels: 1, //录音通道数
  136. encodeBitRate: 192000, //编码码率
  137. format: 'mp3', //音频格式,有效值aac/mp3
  138. frameSize: 50 //指定帧大小,单位 KB
  139. };
  140. //开始录音,在开始录音回调中feed音频片
  141. recorderManager.start(options);
  142. //监听录音结束事件
  143. recorderManager.onStop((res) => {
  144. this.setData({
  145. tempFilePath: res.tempFilePath,
  146. });
  147. this.uploadAudio(res.tempFilePath)
  148. });
  149. } else {
  150. this.stopRecording()
  151. }
  152. },
  153. stopRecording() {
  154. clearInterval(this.dsq)
  155. this.innerAudioContext.stop();
  156. recorderManager.stop();
  157. this.setData({
  158. state: 'after',
  159. tens: this.data.configure.bgMusicLength[0],
  160. bits: this.data.configure.bgMusicLength[1]
  161. })
  162. },
  163. uploadAudio(recordSource) {
  164. this.setData({
  165. uploadState: true
  166. });
  167. const uploadTask = wx.uploadFile({
  168. url: 'https://reader-api.ai160.com//file/upload',
  169. filePath: recordSource,
  170. name: '朗读录音',
  171. header: {
  172. uid: wx.getStorageSync('uid')
  173. },
  174. success: (res) => {
  175. const formateRes = JSON.parse(res.data);
  176. let audioPath = formateRes.data;
  177. this.setData({
  178. audioPath
  179. })
  180. this.uploadActivity()
  181. },
  182. })
  183. },
  184. // 上传贺卡
  185. async uploadActivity() {
  186. this.createActivityImg('upload').then(async res => {
  187. let cardUrl = await this.uploadFile(res)
  188. let data = {
  189. audioPath: this.data.audioPath,
  190. // 生成贺卡图片地址
  191. cardUrl,
  192. toText: this.data.configure.toText,
  193. fromText: this.data.configure.fromText,
  194. templateId: this.data.id
  195. }
  196. console.log(data, 'data');
  197. let greetingCard = await saveActivity(data)
  198. console.log('贺卡生成', greetingCard);
  199. this.setDuration('endTime', greetingCard.duration)
  200. this.setData({
  201. greetingCard,
  202. uploadState: false
  203. })
  204. await actionRecord({
  205. action: 'NEW_YEAR_ACTIVITY_GENERATE_TEMPLATE',
  206. targetContent: this.data.id
  207. })
  208. })
  209. },
  210. playUserAudio() {
  211. if (!this.innerAudioContext) {
  212. this.innerAudioContext = wx.createInnerAudioContext();
  213. }
  214. if (this.data.userAudioState) {
  215. this.innerAudioContext.stop();
  216. this.setData({
  217. userAudioState: false
  218. })
  219. } else {
  220. this.innerAudioContext.src = this.data.greetingCard.audioPath;
  221. this.innerAudioContext.onTimeUpdate(() => {
  222. this.setDuration('playTime', this.innerAudioContext.currentTime)
  223. this.setData({
  224. vProgress: Math.ceil((Math.ceil(this.innerAudioContext.currentTime) / this.innerAudioContext.duration) * 100)
  225. })
  226. })
  227. this.innerAudioContext.play();
  228. this.setData({
  229. userAudioState: true
  230. })
  231. }
  232. },
  233. bindKeyInput(e) {
  234. if (e.currentTarget.dataset.type == 'from') {
  235. this.setData({
  236. 'configure.fromText': e.detail.value
  237. })
  238. } else if (e.currentTarget.dataset.type == 'to') {
  239. this.setData({
  240. 'configure.toText': e.detail.value
  241. })
  242. }
  243. },
  244. focusInput({
  245. currentTarget
  246. }) {
  247. if (currentTarget.dataset.input == 'from') {
  248. this.setData({
  249. focusFrom: true
  250. })
  251. } else {
  252. this.setData({
  253. focusTo: true
  254. })
  255. }
  256. },
  257. // 上传图片
  258. uploadFile(filePath) {
  259. return new Promise((resolve, reject) => {
  260. wx.uploadFile({
  261. url: 'https://reader-api.ai160.com/file/upload',
  262. filePath,
  263. name: '头像',
  264. header: {
  265. uid: wx.getStorageSync('uid')
  266. },
  267. success: (res) => {
  268. const result = JSON.parse(res.data).data;
  269. resolve(result)
  270. }
  271. })
  272. })
  273. },
  274. // 生成活动图片
  275. createActivityImg(createType = 'share') {
  276. return new Promise(async (resolve, reject) => {
  277. if (createType == 'share') {
  278. let title = await getShareText({
  279. cardReadId: this.data.greetingCard.id
  280. })
  281. resolve({
  282. title,
  283. path: `/pages/greeting/index?uid=${wx.getStorageSync('uid')}&cardId=${this.data.greetingCard.id}`,
  284. imageUrl: this.data.greetingCard.cardUrl
  285. })
  286. }
  287. let context = wx.createSelectorQuery();
  288. context
  289. .select('#share')
  290. .fields({
  291. node: true,
  292. size: true
  293. }).exec((res) => {
  294. const canvas = res[0].node;
  295. const ctx = canvas.getContext('2d');
  296. const dpr = wx.getSystemInfoSync().pixelRatio;
  297. canvas.width = res[0].width * dpr;
  298. canvas.height = res[0].height * dpr;
  299. ctx.scale(dpr, dpr);
  300. let avatar = canvas.createImage();
  301. avatar.src = this.data.avatar
  302. avatar.onload = () => {
  303. ctx.drawImage(avatar, this.data.configure.templateBase.photoLeft / 2, this.data.configure.templateBase.photoTop / 2, this.data.configure.templateBase.photoWidth / 2, this.data.configure.templateBase.photoHeight / 2);
  304. let bgImg = canvas.createImage();
  305. bgImg.src = this.data.configure.bgImg
  306. bgImg.onload = () => {
  307. ctx.drawImage(bgImg, 0, 0, 375, 300);
  308. ctx.font = `${this.data.configure.fromFontSize/2}px PingFang`;
  309. ctx.fillStyle = `${this.data.configure.toColor}`;
  310. let toLeft = 0
  311. if (this.data.configure.toTextAlign == 'left') {
  312. toLeft = this.data.configure.templateBase.toLeft / 2
  313. } else if (this.data.configure.toTextAlign == 'right') {
  314. toLeft = this.data.configure.templateBase.toLeft / 2 + (this.data.configure.templateBase.toWidth / 2 - ctx.measureText(this.data.configure.toText).width)
  315. } else if (this.data.configure.toTextAlign == 'center') {
  316. toLeft = this.data.configure.templateBase.toLeft / 2 + ((this.data.configure.templateBase.toWidth / 2 - ctx.measureText(this.data.configure.toText).width) / 2)
  317. }
  318. ctx.fillText(this.data.configure.toText, toLeft, this.data.configure.templateBase.toTop / 2 + this.data.configure.fromFontSize / 2)
  319. ctx.fillStyle = `${this.data.configure.fromColor}`;
  320. let fromLeft = 0
  321. if (this.data.configure.fromTextAlign == 'left') {
  322. fromLeft = this.data.configure.templateBase.fromLeft / 2
  323. } else if (this.data.configure.fromTextAlign == 'right') {
  324. fromLeft = this.data.configure.templateBase.fromLeft / 2 + (this.data.configure.templateBase.fromWidth / 2 - ctx.measureText(this.data.configure.fromText).width)
  325. } else if (this.data.configure.fromTextAlign == 'center') {
  326. fromLeft = this.data.configure.templateBase.fromLeft / 2 + ((this.data.configure.templateBase.fromWidth / 2 - ctx.measureText(this.data.configure.fromText).width) / 2)
  327. }
  328. ctx.fillText(this.data.configure.fromText, fromLeft, this.data.configure.templateBase.fromTop / 2 + this.data.configure.toFontSize / 2)
  329. setTimeout(() => {
  330. wx.canvasToTempFilePath({
  331. canvas: canvas,
  332. success(res) {
  333. resolve(res.tempFilePath)
  334. },
  335. fail(res) {
  336. reject()
  337. }
  338. }, this)
  339. }, 1000)
  340. }
  341. }
  342. })
  343. })
  344. },
  345. onShareAppMessage({
  346. from,
  347. }) {
  348. if (from == 'button') {
  349. actionRecord({
  350. action: 'NEW_YEAR_ACTIVITY_SEND_BLESSING',
  351. })
  352. const promise = new Promise(resolve => {
  353. this.createActivityImg().then(res => {
  354. resolve(res)
  355. })
  356. })
  357. return {
  358. title: '请欣赏我的课文朗读作品,点赞+评论。',
  359. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  360. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png',
  361. promise
  362. }
  363. } else {
  364. return {
  365. title: '课文朗读,从未如此有趣。',
  366. path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
  367. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png'
  368. }
  369. }
  370. },
  371. onShareTimeline() {
  372. return {
  373. title: '拜年还能这么玩?语音贺卡超有趣,点我开玩!',
  374. query: `uid=${wx.getStorageSync('uid')}&id=${this.data.id}`,
  375. imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/xkx_logo.jpg'
  376. }
  377. },
  378. // 设置时间文案
  379. setDuration(label, s) {
  380. let t = '';
  381. s = Math.ceil(s);
  382. if (s > -1) {
  383. let min = Math.floor(s / 60) % 60;
  384. let sec = s % 60;
  385. if (min < 10) {
  386. t += "0";
  387. }
  388. t += min + ":";
  389. if (sec < 10) {
  390. t += "0";
  391. }
  392. t += sec;
  393. }
  394. this.setData({
  395. [label]: t,
  396. })
  397. },
  398. onHide() {
  399. recorderManager.stop()
  400. this.innerAudioContext.stop()
  401. },
  402. onUnload() {
  403. recorderManager.stop()
  404. this.innerAudioContext.stop()
  405. }
  406. })