一、方式1:登陆系统后进行播放,即在浏览器端
需要在JSP页面编写相关代码
<div id="midea" style="display: none;"> <object id='player' height='100' width='200' classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'> <param name='AutoStart' value='0' /> <param name='Balance' value='0' /> <param name='enabled' value='-1' /> <param name='EnableContextMenu' value='-1' /> <param name='url' value='${pageContext.request.contextPath}/player/bestduanxin.wav' /> <param name='volume' value='100' /> <param name='uiMode' value='mini' /> </object> </div>
在js脚本里调用
document.getElementById('player').controls.play(); setTimeout(stopPlayer,6000); function stopPlayer(){ document.getElementById('player').controls.stop(); }
二、方式2:不用登陆即可播放,即在服务器端
需在java后台编写相关代码
import java.applet.Applet; import java.applet.AudioClip; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import javax.servlet.http.HttpServletRequest; public class AudioPlayer { public static void player(HttpServletRequest request){ URL audioUrl=null; try { //项目URL根路径 String path = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); //音频资源地址 audioUrl = new URL(path+"/player/bestduanxin.wav"); //创建音频播放类 final AudioClip audioClass=Applet.newAudioClip(audioUrl); audioClass.loop(); //new一个线程执行停止播放 TimerTask task = new TimerTask() { @Override public void run() { audioClass.stop(); } }; //new一个定时器,指定播放若干秒后执行停止播放 Timer timer = new Timer(); timer.schedule(task, GetPropertiesValue.getTimes()*GetPropertiesValue.getDuration()); } catch (Exception e) { e.printStackTrace(); } } }
附获取音频文件时长的方法
File file = new File(url.substring(0, url.indexOf("WEB-INF"))+"player/bestduanxin.wav");
Clip clip = AudioSystem.getClip(); AudioInputStream ais = AudioSystem.getAudioInputStream(file); clip.open(ais);
//得到的时间为微秒(μs),除以1000得到毫秒(ms)数 System.out.println(clip.getMicrosecondLength()/1000);