audioCtxFactory.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // 每一个音频消息都有自己的 ctx。
  2. // 可以有多个 ctx,每次播放都能知道是哪个 ctx 在调用,从而让其他的 ctx pause。
  3. // 消息销毁,记得处理 ctx。
  4. // 主要是同步跨 ctx 的操作,保证只有一个 ctx 播放
  5. let allCtx = {};
  6. let inUseCtx = null;
  7. let allComm = {}
  8. function proxier(ctx) {
  9. let __play__ = ctx.play;
  10. let __pause__ = ctx.pause;
  11. ctx.play = playProxier;
  12. ctx.pause = pauseProxier;
  13. function playProxier() {
  14. // 如果正在播放的不是自己,暂停
  15. if (inUseCtx && inUseCtx != this) {
  16. inUseCtx.pause();
  17. }
  18. __play__.call(this);
  19. inUseCtx = this;
  20. }
  21. function pauseProxier() {
  22. // 只有是自己才 pause
  23. if (inUseCtx == this) {
  24. __pause__.call(this);
  25. }
  26. }
  27. }
  28. module.exports = {
  29. getCtx(mid) {
  30. let returnCtx = allCtx[mid];
  31. if (!returnCtx) {
  32. returnCtx = wx.createInnerAudioContext();
  33. allCtx[mid] = returnCtx;
  34. proxier(returnCtx);
  35. }
  36. return returnCtx;
  37. },
  38. getAllCtx() {
  39. wx.setStorageSync("allCtx", JSON.stringify(Object.keys(allCtx)));
  40. return allCtx
  41. },
  42. getCommponet(mid, comm) {
  43. let curComm = allComm[mid]
  44. if (!curComm) {
  45. allComm[mid] = comm
  46. }
  47. return allComm
  48. }
  49. };