安装

npm install vue-audio --save

页面

     <audio controls="controls" hidden src="./static/audio/tsy.wav" ref="audio"></audio>
 this.$refs.audio.currentTime = 0; //从头开始播放提示音
          this.$refs.audio.play(); //播放

<audio id="resource" :src="audioSrc" controls autoplay="autoplay"  v-show='yinpinshow'></audio>

自动播放autoplay=“autoplay”
隐藏页面元素v-show=‘yinpinshow’

初始化音频

 data() {
        return {
          audioSrc:require('@/assets/Jay.mp3'),
          yinpinshow:false
        }
 }

动态改变音频地址

this.audioSrc=require('@/assets/hgtc.mp3')

配置webpack.base.conf.js

  {
   test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
   loader: 'url-loader',
   options: {
     limit: 10000,
     // name: utils.assetsPath('media/[name].[hash:7].[ext]')
     name: utils.assetsPath('assets/[name].[hash:7].[ext]')
   }
 },
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
              try {
                  var context = new window.AudioContext();;
                  var source = null;
                  var audioBuffer = null;
                  function stopSound() {
                      if (source) {
                          source.stop(0); //立即停止
                      }
                  }
                  function playSound() {
                      source = context.createBufferSource();
                      source.buffer = audioBuffer;
                      source.loop = false; //循环播放
                      source.connect(context.destination);
                      source.start(0); //立即播放
                  }
                  function initSound(arrayBuffer) {
                      context.decodeAudioData(arrayBuffer, function(buffer) { //解码成功时的回调函数
                          audioBuffer = buffer;
                          playSound();
                      }, function(e) { //解码出错时的回调函数
                          console.log('Error decoding file', e);
                      });
                  }
                  function loadAudioFile(url) {
                      var xhr = new XMLHttpRequest(); //通过XHR下载音频文件
                      xhr.open('GET', url, true);
                      xhr.responseType = 'arraybuffer';
                      xhr.onload = function(e) { //下载完成
                          initSound(this.response);
                      };
                      xhr.send();
                  }
                  loadAudioFile('./static/audio/tsy.mp3');
                  $("#stop").click(function() {
                      stopSound();
                  });
              } catch (e) {
                  console.log('!Your browser does not support AudioContext');
              }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐