h5添加音乐

时间:2023-12-11 16:07:32

http://changziming.com/post-209.html

  • 加入HTML代码,因为是绑定在每一页的右上方(或者其他位置),定位用了fixed,所以在页面底部/body之前加上html代码
    <span id="musicControl">
    <a id="mc_play" class="stop" onclick="play_music();">
    <audio id="musicfx" loop="loop" autoplay="autoplay">
    <source src="./src/audio/audio.mp3" type="audio/mpeg">
    </audio>
    </a>
    </span>

      source 标签里面对应的音频链接换为自己的音频连接哦。

  • 网页头部加入CSS代码
    /* music */
    @-webkit-keyframes reverseRotataZ{
    %{-webkit-transform: rotateZ(0deg);}
    %{-webkit-transform: rotateZ(-360deg);}
    }
    @-webkit-keyframes rotataZ{
    %{-webkit-transform: rotateZ(0deg);}
    %{-webkit-transform: rotateZ(360deg);}
    }
    #musicControl { position:fixed;right:10px;top:20px;margin-top:;display:inline-block;z-index:}
    #musicControl a { display:inline-block;width:25px;height:25px;overflow:hidden;background:url('./src/images/mcbg.png') no-repeat;background-size:%;}
    #musicControl a audio{width:%;height:56px;}
    #musicControl a.stop { background-position:left bottom;}
    #musicControl a.on { background-position:0px 1px;-webkit-animation: reverseRotataZ .2s linear infinite;}
    #music_play_filter{width:%;height:%;overflow:hidden;position:fixed;top:;left:;z-index:;}
    • 添加对应的JS控制方法
    • function play_music(){
      if ($('#mc_play').hasClass('on')){
      $('#mc_play audio').get().pause();
      $('#mc_play').attr('class','stop');
      }else{
      $('#mc_play audio').get().play();
      $('#mc_play').attr('class','on');
      }
      $('#music_play_filter').hide();
      event.stopPropagation(); //阻止冒泡
      }
      function just_play(id){
      $('#mc_play audio').get().play();
      $('#mc_play').attr('class','on');
      if (typeof(id)!='undefined'){
      $('#music_play_filter').hide();
      }
      event.stopPropagation(); //阻止冒泡
      }
      function is_weixn(){
      return false;
      var ua = navigator.userAgent.toLowerCase();
      if(ua.match(/MicroMessenger/i)=="micromessenger") {
      return true;
      } else {
      return false;
      }
      }
      var play_filter=document.getElementById('music_play_filter');
      play_filter.addEventListener('click', function(){
      just_play();
      });
      play_filter.addEventListener('touchstart', function(){
      just_play();
      });
      play_filter.addEventListener('touchend', function(){
      just_play();
      });
      play_filter.addEventListener('touchmove', function(){
      just_play();
      });
      play_filter.addEventListener('mousedown', function(){
      just_play();
      });
      play_filter.addEventListener('mouseup', function(){
      just_play();
      });
      play_filter.addEventListener('mousemove',function(){
      just_play();
      });
      window.onload=function(){
      if (!is_weixn()){
      just_play();
      }
      }

      这里还加入了一个方法判断是否是在微信内打开,如果不是在微信内就自动播放,在微信内部需要点击按钮才变换为播放状态。

    • demo演示:http://changziming.com/demo/audioplay/