需要与HTMLplayer结合使用JavaScript的帮助

时间:2019-05-06 04:18:46

标签: javascript

我想创建一个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>

4 个答案:

答案 0 :(得分:0)

如果我了解您要执行的操作,则可以通过将音频元素与控件属性放在内部放置在body元素中来实现。祝你好运!

答案 1 :(得分:0)

尽管可行,但不建议使用 class ApiRepository { final String _baseUrl = "http://myserver/api"; Dio _dio; ApiProvider() { BaseOptions options = new BaseOptions( baseUrl: _baseUrl, receiveTimeout: 5000, connectTimeout: 5000); _dio = new Dio(options); } Future<LoginResponse> authenticate(Map<String, String> body) async { try { Response response = await _dio.post(_baseUrl + "/authenticate", data: body); print(response.data); return LoginResponse.fromJson(response.data); } catch (error, stacktrace) { print("Exception occured: $error stackTrace: $stacktrace"); return LoginResponse.withError(_handleError(error)); } } 关键字创建数组-而是使用文字数组:

new let arr =
new Array()

使用 let arr = [] 创建一个对象,而不创建在DOM中呈现的HTMLMediaElement。为了获得默认控件,我们需要以HTML编写标记或动态创建音频标签,然后使用JavaScript将其附加到DOM。

HTML
请注意,实际上需要使用new Audio()属性才能使标记可见。

controls

JavaScript
这是用于动态添加与上面相同的音频标签的最小脚本。

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

以下演示的播放列表可以手动控制并自动循环播放。演示中评论了详细信息。

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'
}

答案 2 :(得分:0)

使用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>

答案 3 :(得分:0)

解决了!我使用的iframe在自动播放模式下加载了带有播放列表的页面。通常在Chrome中这还不够,请自动播放 不起作用。我使用了一个名为sil.mp3的空mp3(允许自动播放)的embed标签来触发浏览器上的音频;在这 加载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