jquery:使用 SoundManager 2 创建简单的网页音频播放器
官网:http://www.schillmania.com/projects/soundmanager2/
HTML5 标准中加入了两个非常强大的标签 audio
和 video
,让我们在网页中嵌入视频和音频变得非常方便,但是不幸的是目前用户所使用的有很大一部分浏览器都是老版本的,并不支持这两个标签,这使前端开发者们很困扰,这里介绍一款相对来讲支持浏览器比较多的网页音频播放器 ------ SoundManager 2。
以下是 SoundManager 2 支持的浏览器版本,你没看错,它甚至支持 IE5:
- Firefox (all versions), Windows/Mac
- Safari 1.3+ (Mac) / All Windows versions
- Mobile Webkit: iOS 4.0 devices, iPad 3.2 (original iPad iOS release) and newer
- Android (2.3+, confirmed on 2.3.3.)
- Google Chrome (all versions/OSes)
- Internet Explorer 5.0+, Windows
- Opera 9.10 (slightly buggy, 9.5+ ideal), Windows/Mac
- Netscape 8.0+, Windows/Mac
- Firefox 1.5+, Linux (Flash 9 beta).
创建一个简单的音频播放器
下面将演示如何创建一个简单的音频播放器:
播放器功能
- 播放和暂停
- 取消和重新播放
- 加大/减小声音
- 快进/快退 30 秒
- 显示播放进度
- 显示当前音量
根据上面的列表,我们需要 6 个按钮,所以我们现在 HTML 中生成 6 个按钮控件。
<div class="player"> <div class="player__audio-info"> <div> Played <span class="player__time-elapsed">-</span> of <span class="player__time-total">-</span> <button class="player__previous button button--small">Move back</button> <button class="player__next button button--small">Move forth</button> </div> <div> Volume: <span class="player__volume-info">100</span> <button class="player__volume-down button button--small">Volume down</button> <button class="player__volume-up button button--small">Volume up</button> </div> </div> <button class="player__play button button--large">Play</button> <button class="player__stop button button--large">Stop</button> </div>
添加一些样式
.player { display: inline-block; width: 300px; padding: 5px; background-color: #E3E3E3; border: 1px solid #000000; } .player span { font-weight: bold; } .button { text-indent: 200%; white-space: nowrap; overflow: hidden; border: none; padding: 0; background: rgba(255,255,255,0); cursor: pointer; vertical-align: bottom; } .button--small { width: 19px; height: 19px; } .button--large { width: 48px; height: 48px; } .player__audio-info { padding-bottom: 5px; border-bottom: 1px dotted #000000; } .player__audio-info div + div { margin-top: 10px; } .player__volume-info { display: inline-block; width: 1.5em; } .player__play { background-image: url("http://i60.tinypic.com/14mbep2.png"); } .player__play.is-playing { background-image: url("http://i57.tinypic.com/idyhd2.png"); } .player__stop { background-image: url("http://i61.tinypic.com/35mehdz.png"); } .player__previous { background-image: url("http://i60.tinypic.com/sdihc5.png"); } .player__next { background-image: url("http://i57.tinypic.com/2s1nm77.png"); } .player__volume-down { background-image: url("http://i60.tinypic.com/331nom0.png"); } .player__volume-up { background-image: url("http://i60.tinypic.com/ekkc1t.png"); }
添加操作的 JavaScript 代码:
function formatMilliseconds(milliseconds) { var hours = Math.floor(milliseconds / 3600000); milliseconds = milliseconds % 3600000; var minutes = Math.floor(milliseconds / 60000); milliseconds = milliseconds % 60000; var seconds = Math.floor(milliseconds / 1000); milliseconds = Math.floor(milliseconds % 1000); return (hours > 0 ? hours : '0') + ':' + (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds + ':' + (milliseconds < 100 ? '0' : '') + (milliseconds < 10 ? '0' : '') + milliseconds; } var player = { btnPlay: document.querySelector('.player__play'), btnStop: document.querySelector('.player__stop'), btnPrevious: document.querySelector('.player__previous'), btnNext: document.querySelector('.player__next'), btnVolumeDown: document.querySelector('.player__volume-down'), btnVolumeUp: document.querySelector('.player__volume-up'), timeElapsed: document.querySelector('.player__time-elapsed'), timeTotal: document.querySelector('.player__time-total'), volume: document.querySelector('.player__volume-info') }; var audio = null; soundManager.setup({ useFastPolling: true, useHighPerformance: true, onready: function() { audio = soundManager.createSound({ id: 'audio', url: 'http://freshly-ground.com/data/audio/mpc/20090119%20-%20Untitled%20Groove.mp3', whileloading: function() { player.timeTotal.textContent = formatMilliseconds(audio.durationEstimate); }, whileplaying: function() { player.timeElapsed.textContent = formatMilliseconds(audio.position); }, onload: function() { player.timeTotal.textContent = formatMilliseconds(audio.duration); }, onfinish: function() { var event; try { // Internet Explorer doesn't like this statement event = new Event('click'); } catch (ex) { event = document.createEvent('MouseEvent'); event.initEvent('click', true, false); } player.btnStop.dispatchEvent(event); } }); } }); player.btnPlay.addEventListener('click', function() { if (audio === null) { return; } if (audio.playState === 0 || audio.paused === true) { audio.play(); this.classList.add('is-playing'); } else { audio.pause(); this.classList.remove('is-playing'); } }); player.btnStop.addEventListener('click', function() { if (audio === null) { return; } audio.stop(); document.querySelector('.player__time-elapsed').textContent = formatMilliseconds(0); player.btnPlay.classList.remove('is-playing'); }); player.btnVolumeDown.addEventListener('click', function() { if (audio === null) { return; } var volume = audio.volume - 10 < 0 ? 0 : audio.volume - 10; audio.setVolume(volume); player.volume.textContent = volume; }); player.btnVolumeUp.addEventListener('click', function() { if (audio === null) { return; } var volume = audio.volume + 10 > 100 ? 100 : audio.volume + 10; audio.setVolume(volume); player.volume.textContent = volume; }); player.btnPrevious.addEventListener('click', function() { if (audio === null) { return; } var position = audio.position - 30000 < 0 ? 0 : audio.position - 30000; audio.setPosition(position); player.timeElapsed.textContent = formatMilliseconds(audio.position); }); player.btnNext.addEventListener('click', function() { if (audio === null) { return; } var position = audio.position + 30000 > audio.duration ? audio.duration : audio.position + 30000; if (position === audio.duration) { var event; try { // Internet Explorer doesn't like this statement event = new Event('click'); } catch (ex) { event = document.createEvent('MouseEvent'); event.initEvent('click', true, false); } player.btnStop.dispatchEvent(event); } else { audio.setPosition(position); player.timeElapsed.textContent = formatMilliseconds(audio.position); } });
[实例] 使用JS播放声音——SoundManager 2
官方文档写得很详细,好东西
写个Demo
需要的文件有:下载soundmanager2包中的script文件夹和swf文件夹
Demo/ - index.html Demo/script/ - jquery-1.8.2.min.js - soundmanager2-nodebug-jsmin.js Demo/swf/ - soundmanager2_flash_xdomain.zip - soundmanager2_flash9_debug.swf - soundmanager2_flash9.swf - soundmanager2_debug.swf - soundmanager2.swf Demo/sound/ - msg.mp3
index.html
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>SoundDemo</title> <script type="text/javascript" src="script/soundmanager2-nodebug-jsmin.js"></script> <script type="text/javascript" src="script/jquery-1.10.0.min.js"></script> <script type="text/javascript"> soundManager.setup({ url: 'swf/', //swf文件夹的位置 onready: function() { soundManager.createSound({ id: 'msg', autoLoad: true, autoPlay: false, url: 'sound/msg.mp3' //mp3文件的位置 }); } }); $(document).ready(function () { $('#play').click(function () { soundManager.play('msg'); //点击按钮可播放 }); }); </script> </head> <body> <input type='button' id='play' value='Play' /> </body> </html>
遇到的问题
- 需要把Demo部署到服务器上才能正常, 否则还是会有?跨域的问题?(应该是这个问题吧), 不能加载本地文件. (意思是: 本地直接打开index.html是不能播放的, 但我上传到博客的服务器上就能播放了..有人不理解这个 - - 搜索"跨域"相关)
- 用的.wav文件在chrome中能正常播放, 但在IE中不能播放, 转成.mp3文件后就都可以正常播放了
将代码添加到我自己写的IM里成功播放声音
参考文档:
- Ext:在Ext中播放声音(mp3等)
- tip:如何原生播放声音
原文:http://zoeyyoung.github.io/sound-manager-2-web-im.html
SoundManager属性
soundManager对象有许多可配置的属性,确定Flash的路径和其他行为。下面是SoundManager 2默认的属性,这适合大多数场合,一般情况下你不需要更改它们。
soundManager.url = “/path/to/swf-files/ ” ;
//SM2可以找到Flash影片(soundmanager2.swf,soundmanager2_flash9.swf和调试版本等)的路径。注意:如果没有设置,SM2将追加正确的SWF文件名,对flashVersion和debugMode设置。
soundManager.allowScriptAccess = “always “;
//运行SWF(对象/嵌入属性)方式 可选:”always” or “sameDomain”
soundManager.audioFormats = { … };
//定义支持哪种音频类型(默认情况下为MP3。)
soundManager.bgColor =” #FFFFFF “;
// 背景颜色。
soundManager.consoleOnly = true ;
//如果控制台正在使用,不创建或写入#soundmanager-debug
soundManager.debugMode = true ;
//是否启用调试模式
soundManager.debugFlash = false ;
//是否启用调试里面的SWF输出,解决闪存/浏览器的问题
soundManager.flashVersion = 8 ;
//flash版本(8或9)。一些API功能要求9。
soundManager.flashPollingInterval = null ;
//毫秒,影响加载回调函数频率。如果为null,则使用默认50毫秒。
soundManager.html5PollingInterval = null casino online ;
//毫秒,影响加载回调函数频率。如果为null,运行本地的HTML5更新事件。
soundManager.html5Test = /^(probably|maybe)$/i jameshallison casino ;
//测试HTML5的音频格式。也可用/^probably$/i
soundManager.flashLoadTimeout = 1000 ;
//毫秒 等待Flash视频加载的时间(0 =无穷) 超时显示加载失败
soundManager.noSWFCache = false ;
//如果为TURE,在缓存文件上追加?ts={date}以释放缓存
soundManager.preferFlash = true ;
//是否用到useHTML5audio。目前,如果为 ture并且flash支持的话,将使用MP3/MP4 flash,因为HTML5音频在浏览器中显示有问题。
soundManager.useConsole = true ;
//如果console.log()可用,则使用(否则,写入#soundmanager-debug 元素)
soundManager.useFlashBlock = false ;
//需要flashblock.css,看演示效果时,是否用到flash blockers 。
soundManager.useHighPerformance =false ;
//增强flash显示效果
soundManager.useHTML5Audio = ture ;
//如果API支持,则使用HTML5 Audio() (大多数Safari浏览器,浏览器版本),火狐(没有MP3/MP4)。
soundManager.waitForWindowLoad = false ;
//window.onload()执行完后,才运行soundManager.onload
soundManager.wmode = NULL ;
//flash渲染模式 – 可为:null, “transparent”, or “opaque” (最后两个允许使用z-index)
相关推荐
preserve log:勾选,页面发生跳转,接口不丢失;;Disable cache:不使用缓存,勾选,拿服务器的缓存;不勾选,用本地缓存;;All那列,表示浏览器的请求类型,对应下面的列type;