audio.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. export default {
  2. state:{
  3. // 存放全局事件
  4. events:[],
  5. // 录音管理器
  6. RECORD:null,
  7. RecordTime:0,
  8. RECORDTIMER:null,
  9. sendVoice:null,
  10. onStart:null,
  11. AUDIO:null,
  12. vudioEnd:null
  13. },
  14. mutations:{
  15. // 初始化录音管理器
  16. initRECORD(state){
  17. state.RECORD = uni.getRecorderManager();
  18. state.AUDIO = uni.createInnerAudioContext();
  19. // 监听录音开始
  20. state.RECORD.onStart((e)=>{
  21. state.RecordTime = 0
  22. state.RECORDTIMER = setInterval(()=>{
  23. state.RecordTime++
  24. },1000)
  25. // 执行发送
  26. if (typeof state.onStart === 'function') {
  27. state.onStart(e)
  28. }
  29. })
  30. // 监听录音结束
  31. state.RECORD.onStop((e)=>{
  32. if (state.RECORDTIMER) {
  33. clearInterval(state.RECORDTIMER)
  34. state.RECORDTIMER = null
  35. }
  36. // 执行发送
  37. if (typeof state.sendVoice === 'function') {
  38. state.sendVoice(e)
  39. }
  40. });
  41. //语音自然结束时间
  42. state.AUDIO.onEnded((e)=>{
  43. // 执行发送
  44. if (typeof state.vudioEnd === 'function') {
  45. state.vudioEnd(e)
  46. }
  47. })
  48. },
  49. // 注册发送音频事件
  50. regSendVoiceEvent(state,event){
  51. state.sendVoice = event
  52. },
  53. // 注册发送音频事件
  54. regOnStartEvent(state,event){
  55. state.onStart = event
  56. },
  57. // 注册播放音频自然结束事件
  58. regVudioEndEvent(state,event){
  59. state.vudioEnd = event
  60. },
  61. // 注册全局事件
  62. regEvent(state,event){
  63. state.events.push(event)
  64. },
  65. // 执行全局事件
  66. doEvent(state,params){
  67. state.events.forEach(e=>{
  68. // console.log('执行全局事件');
  69. e(params)
  70. })
  71. },
  72. // 注销事件
  73. removeEvent(state,event){
  74. let index = state.events.findIndex(item => {
  75. return item === event
  76. })
  77. if (index !== -1) {
  78. state.events.splice(index,1)
  79. }
  80. }
  81. },
  82. actions:{
  83. // 分发注册全局事件
  84. audioOn({commit},event){
  85. commit('regEvent',event)
  86. },
  87. // 分发执行全局事件
  88. audioEmit({commit},params){
  89. commit('doEvent',params)
  90. },
  91. // 分发注销全局事件
  92. audioOff({commit},event){
  93. commit('removeEvent',event)
  94. }
  95. }
  96. }