inner-audio-mult.uvue 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <template>
  2. <page-head :title="title"></page-head>
  3. <view class="uni-padding-wrap uni-common-mt">
  4. <view class="uni-title">
  5. <text class="uni-title-text">多音频同时播放</text>
  6. </view>
  7. <button type="primary" @tap="play1()" class="uni-btn"> 播放/停止(进度:{{currentTime1}})</button>
  8. <button type="primary" @tap="play2()" class="uni-btn"> 播放/停止(进度:{{currentTime2}})</button>
  9. </view>
  10. </template>
  11. <script>
  12. type AudioPath = {
  13. description : string
  14. src : string
  15. }
  16. export default {
  17. data() {
  18. return {
  19. title: "多音频同时播放",
  20. _audioContext1: null as InnerAudioContext | null,
  21. src: 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3',
  22. _audioContext2: null as InnerAudioContext | null,
  23. playing1: false,
  24. playing2: false,
  25. currentTime1: 0,
  26. currentTime2: 0,
  27. }
  28. },
  29. onReady() {
  30. this._audioContext1 = uni.createInnerAudioContext();
  31. this._audioContext1!.src = this.src
  32. this._audioContext1!.onTimeUpdate((res) => {
  33. this.currentTime1 = this._audioContext1!.currentTime;
  34. })
  35. this._audioContext2 = uni.createInnerAudioContext();
  36. this._audioContext2!.src = this.src
  37. this._audioContext2!.onTimeUpdate((res) => {
  38. this.currentTime2 = this._audioContext2!.currentTime;
  39. })
  40. },
  41. onUnload() {
  42. if (this._audioContext1 != null) {
  43. this._audioContext1!.stop()
  44. this._audioContext1!.destroy()
  45. }
  46. if (this._audioContext2 != null) {
  47. this._audioContext2!.stop()
  48. this._audioContext2!.destroy()
  49. }
  50. },
  51. methods: {
  52. play1() {
  53. if (this._audioContext1 != null) {
  54. this.currentTime1=0
  55. if (this.playing1) {
  56. this._audioContext1!.stop()
  57. } else {
  58. this._audioContext1!.play()
  59. }
  60. }
  61. this.playing1 = !this.playing1
  62. },
  63. play2() {
  64. if (this._audioContext2 != null) {
  65. this.currentTime2=0
  66. if (this.playing2) {
  67. this._audioContext2!.stop()
  68. } else {
  69. this._audioContext2!.play()
  70. }
  71. }
  72. this.playing2 = !this.playing2
  73. }
  74. }
  75. }
  76. </script>
  77. <style>
  78. .formats {
  79. align-items: center;
  80. }
  81. .icon-play {
  82. width: 60px;
  83. height: 60px;
  84. margin: 10px;
  85. }
  86. </style>