回复 刷新

暂无评论

微信小程序--录制音频,播放音频

1.在pages创建一个main文件夹 
2.在main文件夹下创建一个miain.js文件。 
添加代码:

  1. const constant = require('../../utils/constant.js')
  2. const app = getApp()
  3. const recorderManager = wx.getRecorderManager()
  4. const innerAudioContext = wx.createInnerAudioContext()
  5. Page({
  6. data:{
  7. money:"0.00",
  8. userInfo: {},
  9. hasUserInfo: false,
  10. canIUse: wx.canIUse('button.open-type.getUserInfo'),
  11. },
  12. onLoad: function () {
  13. if (app.globalData.userInfo) {
  14. this.setData({
  15. userInfo: app.globalData.userInfo,
  16. hasUserInfo: true
  17. })
  18. } else if (this.data.canIUse){
  19. // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
  20. // 所以此处加入 callback 以防止这种情况
  21. app.userInfoReadyCallback = res => {
  22. this.setData({
  23. userInfo: res.userInfo,
  24. hasUserInfo: true
  25. })
  26. }
  27. } else {
  28. // 在没有 open-type=getUserInfo 版本的兼容处理
  29. wx.getUserInfo({
  30. success: res => {
  31. app.globalData.userInfo = res.userInfo
  32. this.setData({
  33. userInfo: res.userInfo,
  34. hasUserInfo: true
  35. })
  36. }
  37. })
  38. }
  39. },
  40. getlocat:function(){
  41. wx.authorize({
  42. scope: 'scope.record',
  43. success() {
  44. // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
  45. const options = {
  46. duration: 600000,
  47. sampleRate: 44100,
  48. numberOfChannels: 1,
  49. encodeBitRate: 192000,
  50. format: 'mp3',
  51. frameSize: 50
  52. }
  53. recorderManager.start(options)
  54. recorderManager.onStart(() => {
  55. console.log('recorder start')
  56. })
  57. recorderManager.onError((res) => {
  58. console.log(res);
  59. })
  60. }
  61. })
  62. // console.log(app)
  63. },
  64. strop:function(){
  65. recorderManager.stop()
  66. recorderManager.onStop((res) => {
  67. console.log('recorder stop', res)
  68. const { tempFilePath } = res
  69. console.log(tempFilePath)
  70. this.tempFilePath = tempFilePath
  71. })
  72. },
  73. //播放声音
  74. play: function () {
  75. innerAudioContext.autoplay = true
  76. innerAudioContext.src = this.tempFilePath;
  77. innerAudioContext.onPlay(() => {
  78. console.log('开始播放')
  79. })
  80. innerAudioContext.onError((res) => {
  81. console.log(res.errMsg)
  82. console.log(res.errCode)
  83. })
  84. },
  85. })

3.新建一个main.wxml文件 
添加代码如下

  1. <view>
  2. <button bindtap='getlocat'>测试</button>
  3. <button bindtap='strop'>测sss试</button>
  4. <button bindtap="play" >播放录音</button>
  5. </view>
  • 0
  • 0
  • 0