index.js 15 KB

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