【html5 audio】音乐播放,灵动的音符效果 分类: HTML5 ...

html 部分

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" /> 
<title>My Coffee Stream 0.1</title>
<style type="text/css">
html,body,div,img{
	margin:0;
	padding:0;
}
a,a:hover{
	text-decoration:none;
}
.background{
	width:100%;
	position:fixed;
	top:0;
	left:0;
}
.audio_box{
	position:absolute;
	right:20px;
	top:60px;
	width:130px;
	height:80px;
	text-align:center;
	color:#fff;
}
.audio_box .audio_btn_box{
	position:absolute;
	left:60px;
	width:52px;
	z-index:2;
}
</style>
</head>

<body>
<img src="images/cover.png" class="background resizeContainer"/><!--任性地加个背景-->
<div class="audio_box" id="J_audio_box">
	<div class="audio_btn_box">
		<img src="images/play.png" class="icon" />
		<span id="J_audio_txt" class="txt">暂停</span>
	</div>
</div>
<script type="text/javascript" src="js/zepto.js"></script><!--js库文件,网上都有-->
<script type="text/javascript" src="js/coffee.js"></script>
<script type="text/javascript">
var isiOS = navigator.userAgent.match('iPad') || navigator.userAgent.match('iPhone') || navigator.userAgent.match('iPod');
var _this_audio = {
    _audio : null,
    _audio_val : false,
    init : function(){
        var options_audio = {
            loop: true,
            preload: "auto",
            autoplay: "autoplay",
            src: 'YouAndMe.mp3'
        }

        _this_audio._audio = new Audio();

        for (var key in options_audio) {
            _this_audio._audio[key] = options_audio[key];
        }
        _this_audio._audio.load();

        if(isiOS){//由于ios不能自动播放,所以ios的浏览器默认为暂停状态,而其它为自动播放状态
            $('#J_audio_txt').text('播放');
            _this_audio._audio_val = true;
        }

        _this_audio.bindevent();
    },
    audio_play : function(){
        _this_audio._audio_val = false;
        if(_this_audio._audio){
            _this_audio._audio.play();
        }
    },
    audio_pause : function(){
        _this_audio._audio_val = true;
        if (_this_audio._audio){
            _this_audio._audio.pause();
        }
    },
    control : function(){
        if (!_this_audio._audio_val) {
            _this_audio.audio_pause();
        } else {
            _this_audio.audio_play();
        }
    },
    bindevent : function(){
        $('#J_audio_box .audio_btn_box').on('click', _this_audio.control);
        $(_this_audio._audio).on('play',function(){
            _this_audio._audio_val = false;
            $('#J_audio_txt').text('暂停');
            $.fn.coffee.start();
            $('.coffee-steam-box').show(500);
        });
        $(_this_audio._audio).on('pause',function(){
            _this_audio._audio_val = true;
            $('#J_audio_txt').text('播放');
            $.fn.coffee.stop();
            $('.coffee-steam-box').hide(500);
        });
    }
}
var window_h, window_w;
$(document).ready(function(){
	window_w = $(window).width();
	window_h = $(window).height();
	
	$('.resizeContainer').width(window_w).height(window_h);

	$('#J_audio_box').coffee({//灵动的音符初始化
		steams: ["<img src='images/player.png' />", "images/player.png' />"],
		steamHeight: 100,
		steamWidth: 44
	});
	
	_this_audio.init();
});
</script>
</body>
</html>


coffee.js

;(function($, undefined){
  var prefix = '', eventPrefix, endEventName, endAnimationName,
    vendors = { Webkit: 'webkit', Moz: '', O: 'o' },
    document = window.document, testEl = document.createElement('div'),
    supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,
    transform,
    transitionProperty, transitionDuration, transitionTiming, transitionDelay,
    animationName, animationDuration, animationTiming, animationDelay,
    cssReset = {}

  function dasherize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() }
  function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() }

  $.each(vendors, function(vendor, event){
    if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
      prefix = '-' + vendor.toLowerCase() + '-'
      eventPrefix = event
      return false
    }
  })

  transform = prefix + 'transform'
  cssReset[transitionProperty = prefix + 'transition-property'] =
  cssReset[transitionDuration = prefix + 'transition-duration'] =
  cssReset[transitionDelay    = prefix + 'transition-delay'] =
  cssReset[transitionTiming   = prefix + 'transition-timing-function'] =
  cssReset[animationName      = prefix + 'animation-name'] =
  cssReset[animationDuration  = prefix + 'animation-duration'] =
  cssReset[animationDelay     = prefix + 'animation-delay'] =
  cssReset[animationTiming    = prefix + 'animation-timing-function'] = ''

  $.fx = {
    off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined),
    speeds: { _default: 400, fast: 200, slow: 600 },
    cssPrefix: prefix,
    transitionEnd: normalizeEvent('TransitionEnd'),
    animationEnd: normalizeEvent('AnimationEnd')
  }

  $.fn.animate = function(properties, duration, ease, callback, delay){
    if ($.isFunction(duration))
      callback = duration, ease = undefined, duration = undefined
    if ($.isFunction(ease))
      callback = ease, ease = undefined
    if ($.isPlainObject(duration))
      ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration
    if (duration) duration = (typeof duration == 'number' ? duration :
                    ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000
    if (delay) delay = parseFloat(delay) / 1000
    return this.anim(properties, duration, ease, callback, delay)
  }

  $.fn.anim = function(properties, duration, ease, callback, delay){
    var key, cssValues = {}, cssProperties, transforms = '',
        that = this, wrappedCallback, endEvent = $.fx.transitionEnd,
        fired = false

    if (duration === undefined) duration = $.fx.speeds._default / 1000
    if (delay === undefined) delay = 0
    if ($.fx.off) duration = 0

    if (typeof properties == 'string') {
      // keyframe animation
      cssValues[animationName] = properties
      cssValues[animationDuration] = duration + 's'
      cssValues[animationDelay] = delay + 's'
      cssValues[animationTiming] = (ease || 'linear')
      endEvent = $.fx.animationEnd
    } else {
      cssProperties = []
      // CSS transitions
      for (key in properties)
        if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') '
        else cssValues[key] = properties[key], cssProperties.push(dasherize(key))

      if (transforms) cssValues[transform] = transforms, cssProperties.push(transform)
      if (duration > 0 && typeof properties === 'object') {
        cssValues[transitionProperty] = cssProperties.join(', ')
        cssValues[transitionDuration] = duration + 's'
        cssValues[transitionDelay] = delay + 's'
        cssValues[transitionTiming] = (ease || 'linear')
      }
    }

    wrappedCallback = function(event){
      if (typeof event !== 'undefined') {
        if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below"
        $(event.target).unbind(endEvent, wrappedCallback)
      } else
        $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout

      fired = true
      $(this).css(cssReset)
      callback && callback.call(this)
    }
    if (duration > 0){
      this.bind(endEvent, wrappedCallback)
      // transitionEnd is not always firing on older Android phones
      // so make sure it gets fired
      setTimeout(function(){
        if (fired) return
        wrappedCallback.call(that)
      }, (duration * 1000) + 25)
    }

    // trigger page reflow so new elements can animate
    this.size() && this.get(0).clientLeft

    this.css(cssValues)

    if (duration <= 0) setTimeout(function() {
      that.each(function(){ wrappedCallback.call(this) })
    }, 0)

    return this
  }

  testEl = null
})(Zepto)

;(function($){
	$.fn.coffee = function(option){
    // 鍔ㄧ敾瀹氭椂鍣�
    var __time_val=null;
    var __time_wind=null;
    var __flyFastSlow = 'cubic-bezier(.09,.64,.16,.94)';

    // 鍒濆鍖栧嚱鏁颁綋锛岀敓鎴愬搴旂殑DOM鑺傜偣
		var $coffee = $(this);
		var opts = $.extend({},$.fn.coffee.defaults,option);  // 缁ф壙浼犲叆鐨勫€�

    // 婕傛诞鐨凞OM
    var coffeeSteamBoxWidth = opts.steamWidth;
    var $coffeeSteamBox = $('<div class="coffee-steam-box"></div>')
      .css({
        'height'   : opts.steamHeight,
        'width'    : opts.steamWidth,
        'left'     : 60,
        'top'      : -50,
        'position' : 'absolute',
        'overflow' : 'hidden',
        'z-index'  : 0 
      })
      .appendTo($coffee);

    $.fn.coffee.stop = function(){
      clearInterval(__time_val);
      clearInterval(__time_wind);
    }

    $.fn.coffee.start = function(){
      __time_val = setInterval(function(){
        steam();
      }, rand( opts.steamInterval / 2 , opts.steamInterval * 2 ));

      __time_wind = setInterval(function(){
        wind();
      },rand( 100 , 1000 )+ rand( 1000 , 3000))
    }
		return $coffee;
		
    function steam(){	
			var fontSize = rand( 8 , opts.steamMaxSize  ) ;    
      var steamsFontFamily = randoms( 1, opts.steamsFontFamily ); 
      var color = '#'+ randoms(6 , '0123456789ABCDEF' ); 
			var position = rand( 0, 44 );                       
			var rotate = rand(-90,89);                         
			var scale = rand02(0.4,1);                          
      var transform =  $.fx.cssPrefix+'transform';      
          transform = transform+':rotate('+rotate+'deg) scale('+scale+');'

			var $fly = $('<span class="coffee-steam">'+ randoms( 1, opts.steams ) +'</span>');
			var left = rand( 0 , coffeeSteamBoxWidth - opts.steamWidth - fontSize );
			if( left > position ) left = rand( 0 , position );
			$fly
        .css({
          'position'     : 'absolute',
          'left'         : position,
          'top'          : opts.steamHeight,
          'font-size:'   : fontSize+'px',
          'color'        : color,
          'font-family'  : steamsFontFamily,
          'display'      : 'block',
          'opacity'      : 1
        })
        .attr('style',$fly.attr('style')+transform)
        .appendTo($coffeeSteamBox)
        .animate({
  				top		: rand(opts.steamHeight/2,0),
  				left	: left,
  				opacity	: 0
			  },rand( opts.steamFlyTime / 2 , opts.steamFlyTime * 1.2 ),__flyFastSlow,function(){
				  $fly.remove();
				  $fly = null;			
			 });
		};
		
		function wind(){
      var left = rand( -10 , 10 );
      left += parseInt($coffeeSteamBox.css('left'));
      if(left>=54) left=54;
      else if(left<=34) left=34;

      $coffeeSteamBox.animate({
        left  : left 
      } , rand( 1000 , 3000) ,__flyFastSlow);
		};
		
		function randoms( length , chars ) {
			length = length || 1 ;
			var hash = '';                  // 
			var maxNum = chars.length - 1;  // last-one
			var num = 0;                    // fisrt-one
			for( i = 0; i < length; i++ ) {
				num = rand( 0 , maxNum - 1  );
				hash += chars.slice( num , num + 1 );
			}
			return hash;
		};

		function rand(mi,ma){   
			var range = ma - mi;
			var out = mi + Math.round( Math.random() * range) ;	
			return parseInt(out);
		};	

		function rand02(mi,ma){   
			var range = ma - mi;
			var out = mi + Math.random() * range;	
			return parseFloat(out);
		};		
	};

	$.fn.coffee.defaults = {
		steams				    : ['jQuery','HTML5','HTML6','CSS2','CSS3','JS','$.fn()','char','short','if','float','else','type','case','function','travel','return','array()','empty()','eval','C++','JAVA','PHP','JSP','.NET','while','this','$.find();','float','$.ajax()','addClass','width','height','Click','each','animate','cookie','bug','Design','Julying','$(this)','i++','Chrome','Firefox','Firebug','IE6','Guitar' ,'Music' ,'鏀诲煄甯�' ,'鏃呰' ,'鐜嬪瓙澧�','鍟ら厭'], /*婕傛诞鐗╃殑绫诲瀷锛岀绫�*/
		steamsFontFamily	: ['Verdana','Geneva','Comic Sans MS','MS Serif','Lucida Sans Unicode','Times New Roman','Trebuchet MS','Arial','Courier New','Georgia'],  /*婕傛诞鐗╃殑瀛椾綋绫诲瀷*/
		steamFlyTime		  : 5000 , 
		steamInterval	    : 500 ,  
		steamMaxSize		  : 30 ,   
		steamHeight	  	  : 200,   
		steamWidth	      : 300    
	};
	$.fn.coffee.version = '2.0.0'; 
})(Zepto);

效果图:


版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/snow-finland/p/4690166.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值