[英]Need help using javascript with HTMLplayer
我想創建一個html5播放器,它將按順序播放多個音頻文件。 我發現下面的代碼在頁面打開時可以很好地播放文件,但我希望能夠通過播放器和控件來控制音頻。 誰能幫我這個?
var sounds = new Array(new Audio("https://www.w3schools.com/html/horse.mp3"), new Audio("https://www.w3schools.com/html/horse.mp3"), new Audio("https://www.w3schools.com/html/horse.mp3")); var i = -1; playSnd(); function playSnd() { i++; if (i == sounds.length) return; sounds[i].addEventListener('ended', playSnd); sounds[i].play(); }
<!DOCTYPE html> <html> <head> </head> <body> <p /> </body> </html>
您可以通過將音頻元素與控制body元素中的屬性,如果我明白你想做什么做。 祝好運!
雖然它可行,但不建議使用new
關鍵字創建數組 - 而是使用文字數組:
👎 let arr =
new Array()
👍let let arr = []
使用new Audio()
創建一個Object,但不創建在DOM中呈現的HTMLMediaElement。 為了獲得默認控件,我們需要在HTML中編寫標記或動態創建音頻標記並使用JavaScript將其附加到DOM。
HTML
請注意,實際使標簽可見時需要controls
屬性。
<audio src="http://example.com/path/to/file.mp3" controls></audio>
JavaScript的
這是動態添加上述相同音頻標簽的最小腳本。
const audioTag = document.createElement('audio');
audioTag.controls = true;
audioTag.src = "http://example.com/path/to/file.mp3";
document.body.appendChild(audioTag);
以下演示有一個可以手動控制並自動循環的播放列表。 詳細信息在演示中評論。
// Reference <audio> const player = document.querySelector('audio'); // Reference <figcaption> const skip = document.querySelector('.skip'); /* Object - base property is a string of host - path property is an array of strings of each path */ const list = { base: 'http://soundbible.com/mp3/', path: ['chinese-gong-daniel_simon.mp3', 'Dial%20Up%20Modem-SoundBible.com-909377495.mp3', 'Fake%20Applause-SoundBible.com-1541144825.mp3'] }; // Number of paths const size = list.path.length; // Reference <output> const item = document.querySelector('.item'); // Declare counter let counter = 0; // Declare loop flag. let loop = false; /* Function pass list object Ternary that resets count when min and max are exceeded Change the value of <output> to count+1 Change <audio> src to new url interpolated from list .base and .path properties load() and play() audio */ const playlist = list => { let count = counter >= size ? size - 1 : counter < 0 ? 0 : counter; item.value = count + 1; player.src = `${list.base}${list.path[count]}`; player.load(); if (count >= size || count < 0) { player.pause(); } else { player.play(); } return false; } // Reister the ended event on <audio player.onended = function(e) { counter++; playlist(list); if (!loop) { if (counter >= size || counter < 0) { counter = size - 1; e.target.pause(); } } return false; } /* Register <figcaption> to click event Delegate the click event to the e.target e.target always points to the clicked element. */ skip.onclick = function(e) { const target = e.target; if (target.matches('.prev')) { counter--; } else if (target.matches('.next')) { counter++; } else { return false; } playlist(list); }
button, output { font: inherit; display: inline-block; font-size: 1.2rem; cursor: pointer; } .loop.cont::before { content: '\\1f501' } .loop.once::before { content: '\\1f502' }
<!DOCTYPE html> <html> <head> </head> <body> <figure class='box'> <audio src='http://soundbible.com/mp3/chinese-gong-daniel_simon.mp3' controls></audio> <figcaption class='skip'> <button class='prev'>⏪</button> <button class='next'>⏩</button> <output class='item'>1</output> </figcaption> </figure> <script> <!--Place JS here. The end tag of /body> should be the--> <!--only thing to follow the last < script > tag --> </script> </body> </html>
使用jquery1.7嘗試此代碼(假設您在js文件夾中有jq),這里是完整的頁面代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>AudioPlayer-playlist</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery-1.7.js"></script>
<style>
.player{
width:340px;
padding:1px;
border:solid 2px black;
position:relative;
display:block;
background:steelblue;
margin:auto;
}
ul{
padding:0px ;
list-style-type: none;
background:yellow;
height: 280px;
overflow: auto;
margin-bottom:4px;
}
li:nth-child(odd) {
background: silver;
}
li:nth-child(even) {
background: lightGray;
}
#playlist{
margin-top:0px;
position:relative;
width:100%;
padding:0px;
}
audio{
position:relative;
width:98%;
padding:0px;
margin-left:1%;
margin-right:1%;
border-radius:8px;
margin-bottom:0px;
}
.active a{
color:black;
text-decoration:none;
background:lightBlue;
}
li a{
color:black;
font-weight:bold;
padding:5px;
display:block;
text-decoration:none;
}
li a:hover{
text-decoration:none;
background:lightSteelBlue;
}
</style>
<script>
$(window).load(function(){
var audio, playlist, tracks, current;
init();
function init(){
current = 0;
audio = $('audio');
playlist = $('#playlist');
tracks = playlist.find('li a');
len = tracks.length;
audio[0].volume = .60;
playlist.find('a').click(function(e){
e.preventDefault();
link = $(this);
current = link.parent().index();
run(link, audio[0]);
});
audio[0].addEventListener('ended',function(e){
current++;
if(current == len){
current = 0;
link = playlist.find('a')[0];
}else{
link = playlist.find('a')[current];
}
run($(link),audio[0]);
});
}
function run(link, player){
player.src = link.attr('href');
par = link.parent();
par.addClass('active').siblings().removeClass('active');
audio[0].load();
audio[0].play();
}
});
</script>
</head>
<body>
<div class="player">
<ul id="playlist">
<li><a href="audio/01.mp3">song 01</a>
</li>
<li><a href="audio/02.mp3">song 02</a>
</li>
<li><a href="audio/03.mp3">song 03</a>
</li>
<li><a href="audio/04.mp3">song 04</a>
</li>
<li><a href="audio/05.mp3">song 05</a>
</li>
<li><a href="audio/06.mp3">song 06</a>
</li>
<li><a href="audio/07.mp3">song 07</a>
</li>
<li><a href="audio/08.mp3">song 08</a>
</li>
<li><a href="audio/09.mp3">song 09</a>
</li>
<li><a href="audio/10.mp3">song 10</a>
</li>
</ul>
</div>
<audio id="audio" controls type="audio/mpeg">
Sorry, your browser does not support HTML5 audio</audio>
</div>
</body>
</html>
解決了! 我使用iframe在自動播放模式下加載帶有播放列表的頁面。 通常在Chrome中這還不夠,自動播放不起作用。 我使用embed標簽(允許自動播放)和一個名為sil.mp3的空mp3來觸發瀏覽器上的音頻; 以這種方式加載iframe的頁面可以自動播放。 這里是iframe頁面的代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Invisible Playlist Example page</title>
<style>
embed {visibility: hidden;}
iframe {visibility: hidden;}
</style>
</head>
<body
<h3>This page is playing a Playlist even if you can't see
nothing:<br />
there is an iframe that loads audio</h3>
<embed src="audio/sil.mp3" autoplay></embed>
<iframe src="mylist.html"></iframe>
</body>
</html>
這里是用iframe加載的頁面代碼(mylist.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Invisible Playlist Example</title>
<style>
#playlist {display: none;}
audio {display: none;}
</style>
</head>
<body>
<h2>This page is playing a Playlist even if you can't see
nothing:<br />
audio = display:none; and has autoplay, not allowed in Chrome,
Opera</h2>
<div id="playlist">
<audio controls autoplay></audio>
</div>
<script src="mylist.js"></script>
</body>
</html>
最后包含在頁面中的腳本(mylist.js)
(function () {
// Playlist array
var files = [
"audio/song1.mp3",
"audio/song2.mp3",
"audio/song3.mp3"
];
// Current index of the files array
var current = 0;
// Get the audio element
var playlistPlayer = document.querySelector("#playlist audio");
// function that will be call at the end of the previous
function next() {
// Check for last media in the playlist
if (current === files.length - 1) {
current = 0;
} else {
current++;
}
// Change the audio element source
playlistPlayer.src = files[current];
}
// Check if the player is in the DOM
if (playlistPlayer === null) {
throw "Playlist Player does not exists ...";
} else {
// Start the player
playlistPlayer.src = files[current];
// Listen for the playback ended event, to play the next media
playlistPlayer.addEventListener('ended', next, false)
}
})();
這里有一個例子http://giocaroli.xoom.it/pub/test/pag_loadin_playlist.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.