兼容不同浏览器的音频文件(mp3)播放实现

在做一个网站的时候客户提出了令人蛋疼的“新接到单子要有语音提示”的需求,于是花了点功夫去尝试在不通浏览器里播放mp3,wma,wav这些格式,经过测试不太理想,于是想到了用flash播放mp3的想法,这个应该是最通用的吧。。但是需要一个一个swf格式的音频播放器,网上找了好多,都是带按钮的,但是我只需要直接放mp3就行了呀。于是自己用flex写了一个,代码简单的要死。。如下

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   initialize="init()" width="1" height="1"
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:local="*">
	<fx:Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx:Declarations>	
	<fx:Script>
		<![CDATA[
			import flash.media.*;			
			
			private function init():void
			{
				var s:Sound = new Sound(new URLRequest(parameters.audiofile));
				s.play(0,0,null);	
			}				
		]]>
	</fx:Script>
</s:Application>

然后在html里写了一个播放方法,带上flashvars参数,来传递mp3文件的路径:

function play() {
    if (isSoundOn) {//如果声音开启,那么播放,否则不理他
        $(".alert").remove();
        $("body").append("<embed src='../jinanweb.web/Alert/Alert.swf' class='alert' style='position:absolute;margin-top:-1;width:1px;height:1px;z-index:0;' flashvars='audiofile=../jinanweb.web/Alert/Alert.mp3'></embed>");
//这里的flashvars会被swf里获取,不能改名字;audiofile也不能改动,因为上面的flex代码里规定过
    } 
}

var oldCount = 0;var isSoundOn = true;
function checkNewDanZi(type) {//自己的函数,通过ajax轮询来判断有没有新单子,有的话调用Play(),没有的话什么都不do
    //play();
    (function playAlert() {
        var func = this;
        window.setTimeout(function () {
            $.ajax({
                url: "../jinanweb.web/Alert/alert.ashx?t=" + type,
                cache: false,
                success: function (e) {                    
                    if (parseInt(e) > 0) {
                        if (oldCount == 0) { oldCount = e; }
                        else {
                            if (oldCount != e) { play(); oldCount = e; }                            
                        }
                        playAlert();
                    }
                }
            });
        }, 3000);
    })();
}

$(function () {//声音开关控制
    $(".alertbg").live("click", function () {
        if ($(this).attr("src").indexOf("SoundOn") > -1) {
            $(this).hide(100).attr("src", '../jinanweb.web/images/SoundOff.png').show(100);
            isSoundOn = false;
        }
        else {
            $(this).hide(100).attr("src", '../jinanweb.web/images/SoundOn.png').show(100);
            isSoundOn = true;
        }
    });//初始化的时候加上声音图片,我们把它固定到浏览器的左下角
    $("body").append("<img src='../jinanweb.web/images/SoundOn.png' class='alertbg' style='width:23px;height:19px;position:fixed;bottom:10px;z-index:9999;left:0px;' />");
});

如有不足,还望指正。。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值