简体   繁体   English

在HTMLplayer中使用javascript需要帮助

[英]Need help using javascript with HTMLplayer

I want to create an html5 player that will play multiple audio files sequentially. 我想创建一个html5播放器,它将按顺序播放多个音频文件。 I found the code below which works perfectly in playing the files when the page opens, but I want to be able to control the audio with a player and controls. 我发现下面的代码在页面打开时可以很好地播放文件,但我希望能够通过播放器和控件来控制音频。 Can anyone help me with this? 谁能帮我这个?

 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> 

You can do it by placing audio element with controls attribute inside the body element if I understood what you're trying to do. 您可以通过将音频元素与控制body元素的属性,如果我明白你想做什么做。 Good luck! 祝好运!

Although it works, creating arrays with the new keyword is not recommended -- instead use the literal array: 虽然它可行,但不建议使用new关键字创建数组 - 而是使用文字数组:

👎 let arr = 👎 let arr = new Array()
👍 let arr = [] 👍let let arr = []

Using new Audio() creates an Object but not the HTMLMediaElement rendered in the DOM. 使用new Audio()创建一个Object,但不创建在DOM中呈现的HTMLMediaElement。 In order to get the default controls we need to either write the markup in HTML or dynamically create an audio tag and append it to the DOM using JavaScript. 为了获得默认控件,我们需要在HTML中编写标记或动态创建音频标记并使用JavaScript将其附加到DOM。

HTML HTML
Note the controls attribute is needed to actually have the tag visible. 请注意,实际使标签可见时需要controls属性。

<audio src="http://example.com/path/to/file.mp3" controls></audio>

JavaScript JavaScript的
Here's the minimal script to dynamically add the same audio tag as above. 这是动态添加上述相同音频标签的最小脚本。

const audioTag = document.createElement('audio');
audioTag.controls = true;
audioTag.src = "http://example.com/path/to/file.mp3";
document.body.appendChild(audioTag);

The following demo has a playlist that can be controlled manually and loops automatically. 以下演示有一个可以手动控制并自动循环的播放列表。 Details commented in the demo. 详细信息在演示中评论。

 // 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> 

try this code with jquery1.7 (suppose you have jq in js folder), here complete page code 使用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>

Solved! 解决了! I used an iframe that load a page with the playlist in autoplay mode. 我使用iframe在自动播放模式下加载带有播放列表的页面。 Normally in Chrome this is not enough, autoplay doesn'twork. 通常在Chrome中这还不够,自动播放不起作用。 I used embed tag (that allow autoplay) with an empty mp3 called sil.mp3, to trig the audio on the browser; 我使用embed标签(允许自动播放)和一个名为sil.mp3的空mp3来触发浏览器上的音频; in this way the page loaded with iframe can autoplay. 以这种方式加载iframe的页面可以自动播放。 Here the code of the page with the 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>

Here the code of the page loaded with the iframe (mylist.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>

and at last the script (mylist.js) included in the page 最后包含在页面中的脚本(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)
}

})();

an example here http://giocaroli.xoom.it/pub/test/pag_loadin_playlist.html 这里有一个例子http://giocaroli.xoom.it/pub/test/pag_loadin_playlist.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM