在做一個網站的時候客戶提出了令人蛋疼的“新接到單子要有語音提示”的需求,於是花了點功夫去嘗試在不通瀏覽器裡播放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;' />");});
如有不足,還望指正。。