我正在尝试使用html音频播放器,当选择播放曲目列表中的其他歌曲时,src属性会交换。
我编写了下面的代码,它将播放器中的src交换得很好,但即使这个新的src网址已被交换,播放器播放的实际歌曲也不会更新。
非常感谢任何想法。
<!-- PLAYER -->
<div id="player_container">
<div id="player_wrapper">
<audio id="player" controls>
<source src="default_song_url" type="audio/ogg">
<source src="default_song_url" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
</div>
<!-- TRACK LIST (fed through a for loop for other songs) -->
<tr>
<td>Song title</td>
<td><a class="play_song1">Play</a> </td>
<script>
$(document).ready(function(){
$(".play_song1").click(function(){
$("#player_wrapper source").attr("src", "song_1_url");
});
});
</script>
</tr>
&#13;
答案 0 :(得分:1)
只需添加更多详细信息,更大的播放列表以及使用数组即可轻松扩展。下一个改进是JSON。
使用纯JavaScript有时比jQuery更简单,就像音频和视频一样。
getElementById
来引用#player
.src
属性按点表示法更改。.load
src
方法
.play
。addEventListener
用于click事件,但jQuery更容易。 注意:虽然src
属性位于<source>
,但请注意我改为<audio>
。
另请注意:我删除了ogg因为mp3现在已经普及,而且我不会在未来几年看到这种情况发生变化。
另一个注意事项:不要使用<table>
或其任何界面(即tr, th, td
等...)进行布局,使用它们对于数据。
$(document).ready(function() {
// Playlist is an array of 5 songs.²
var playlist = ['balls.mp3', 'pf-righteous.mp3', 'fightclub.mp3', '111.mp3', '00.mp3'];
// A delegated click event is on each li.song
// when triggered the following happens:
$(".song").on('click', function(e) {
// This prevents the anchors from jumping like they normally do.
e.preventDefault();
// $(this) is the li.song that was picked by user. Use .data()
// to determine the li.song's index number.
var song = $(this).data('idx');
// Reference the audio element
var ply = document.getElementById('player');
// This url is the location where the mp3s reside.¹
var base = 'http://glpjt.s3.amazonaws.com/so/av/';
// Here the src is concatenated
// 1. The base¹ URL +
// 2. The playlist array² index is machted with #playlist li.play.³
// 3. After the new src is made, load() the player and play()
ply.src = base + playlist[song];
ply.load();
ply.play();
});
});
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="playerBox">
<div id="playerLayer">
<audio id="player" controls>
<source src="http://glpjt.s3.amazonaws.com/so/av/pf-righteous.mp3" type="audio/mpeg">
</audio>
</div>
<dl id="playlist">
<dt>Playlist</dt>
<!--Each list item has a unique data-idx='x' and an identical .song class.³-->
<a href="#" data-idx="0" class="song">
<dd>Play 0</dd>
</a>
<a href="#" data-idx="1" class="song">
<dd>Play 1</dd>
</a>
<a href="#" data-idx="2" class="song">
<dd>Play 2</dd>
</a>
<a href="#" data-idx="3" class="song">
<dd>Play 3</dd>
</a>
<a href="#" data-idx="4" class="song">
<dd>Play 4</dd>
</a>
</dl>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
&#13;