1、JS播放音乐需要区分浏览器,来使用不用的对象来播放音乐
2、在播放控制上要有【播放】和【停止】来控制音乐的播放
基于以上思路,代码如下:
<SCRIPT type="text/javascript">if(-1 != navigator.userAgent.indexOf("MSIE"))
{
//不是微软IE浏览器,则调用Flash来播放音乐
document.write(' <OBJECT id="Player"')
document.write(' classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6"')
document.write(' width=0 height=0 > <param name="URL" value="a.mp3" /> <param name="AutoStart" value="false" /> </OBJECT>')
}
else
{
//是微软IE浏览器,则调用微软的Player对象来直接播放音乐
document.write(' <OBJECT id="Player"')
document.write(' type="application/x-ms-wmp"')
document.write(' autostart="false" src= "a.mp3" width=0 height=0> </OBJECT>')
}
</SCRIPT>
<input type=button value="播放" onclick="Player.controls.play()" />
<input type=button value="停止" onclick="Player.controls.stop()" />
12
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<audio id="myaudio"></audio>
</body>
<script>
// window.onload = function() {
//页面加载完成之后,通过给audio添加autoplay属性,音频下载完成之后自动播放
// var oAudio = document.getElementById('myaudio')
// oAudio.src = 'Le_Papillon.mp3'
// }
//mp3文件名
var mp3List = [
'Girlfriend.mp3',
'Have A Nice Day.mp3',
'Le Papillon.mp3',
'She Is.mp3',
'Tik Tok.mp3'
],
//文件路径
baseUrl = '../music/'
function getMusic(list) {
var len = list.length,
num = parseInt(<a href="https://www.baidu.com/s?wd=Math.random&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YYmvP9PW0LrHw-uHTkuHTs0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EnHnvP1czPjf3rHn1P1f4P1fkrf" target="_blank" class="baidu-highlight">Math.random</a>()*len, 10),
music = baseUrl + list[num]
if(music) {
return music
} else {
getMusic(list, baseUrl)
}
}
canPlay(playAudio)
//查看是否支持audio标签,如果支持,预加载当前指向mp3文件
function canPlay(callback) {
var currentFile = getMusic(mp3List)
try {
var audio = new Audio()
audio.oncanplay = function() {
callback(currentFile)
}
audio.src = currentFile
audio.load()
}catch(e){
callback(false, e)
}
}
//play
function playAudio(currentFile) {
// Check for audio element support.
if (window.HTMLAudioElement &&currentFile) {
try {
var oAudio = document.getElementById('myaudio')
oAudio.src = currentFile
if (oAudio.paused) {
oAudio.play()
}
else {
oAudio.pause()
}
oAudio.onended = function() {
oAudio.src = getMusic(mp3List)
oAudio.play()
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console &&console.error("Error:" + e))
}
}
}
</script>
</html>