HTML和JavaScript音频播放器

时间:2015-12-08 22:57:30

标签: javascript html audio

我正在使用javascript创建一个HTML的音频播放器而没有jquery。我这样做,它将与此类似 Example 我有第一个表作为下拉列表,我将选择其中一个专辑,相应的歌曲将显示在下一个窗格中,这部分工作正常。我的问题是我不知道如何编码它,以便当我点击中间窗格中的一首歌时,歌曲将显示在最后一个窗格中,同时显示相应的图像,专辑名称和歌曲名称。

这是我的代码,其中包含我的var专辑的缩短版本。我也是初学者,如果代码混乱,请原谅。

<html>
<head>
    <script type="text/javascript" src="music.js"></script>
    <style type="text/css"></style>
</head>    
<body>

    <table width="400" height="400" border="1" style="display: inline-block;">
    <caption>Albums</caption>
<tr>
  <td><p>Please select an album from the list</p>
<select id="album-select" name='Album'>
  <option></option>
</select>
</select>
</td>
</tr>
</table>


<table id="songs-table" width="400" height="400" border="1" style="display: inline-block;">
<caption>Songs</caption>
    <tr>
    </tr>
</table>


<table width="400" height="400" border="1" style="display: inline-block;">
<caption>
Selected Songs
</caption>
<tr>
<td>
  <audio controls='controls'>
    <source src='xxxxx.mp3' type='audio/mpeg'>
    <source src='xxxxx.wav' type='audio/wav'>
    Your browser does not support the audio element.
</audio>
</td>
</tr>
</table>
<script>
var albums=
[
    {   "title":"Birdsong Small Birds",
        "artist":"BBC",
        "artwork":"Wren",
        "tracks":[
            {"title":"Dunnock","mp3":"Birdsong-Dunnock.mp3",
            "lyrics":"The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"},
            {"title":"Robin","mp3":"Birdsong-Robin.mp3",
            "lyrics":"Unusually among British birds, both the male and the femaale robins sing"},

var albumElement  = document.getElementById('album-select');
albumElement.addEventListener('change', function(){
  populateSongs(albumElement.value)
});

for(var i=0;albums.length;i++){
  var option = document.createElement("option");
  option.text = albums[i].title;
  albumElement.add(option)
}

function populateSongs(album) {
  var songsTable  = document.getElementById('songs-table');

  while(songsTable.rows.length > 0) {
    songsTable.deleteRow(0);
  }

  for(var i=0;albums.length;i++){

    if(albums[i].title == album) { 

      for(var track=0;albums[i].tracks.length;track++) {
        var row = songsTable.insertRow(track);
        var cell = row.insertCell(0);    

        cell.innerHTML = albums[i].tracks[track].title;

        cell.setAttribute("file",albums[i].tracks[track].mp3);
        cell.addEventListener('click',function(){
          play(this.getAttribute('file'));
        });

      }
    }
  }


}

function play(song) {
  var audioElement  = document.getElementById('audio-player');

  audioElement.src = song;
  console.log(song);

}
</script>
</body>
</html>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

首先:

  • 您的HTML结构糟糕且不正确
  • 不要写内联css
  • 尝试理解您编写的代码

我没有太多时间来审核所有代码。希望这会帮助你。一些代码行被注释,如果有什么不清楚,请问。

您将需要某种类型的本地服务器,因为您无法在本地文件上使用xhr请求。 如果安装了python,则可以从项目的根目录开始使用python -m SimpleHTTPServer 3001,然后导航到127.0.0.1:3001(或localhost)。或者您可以使用Brackets编辑器的实时预览,它将为您创建本地服务器。 或者,如果您不想运行本地服务器,则可以使用Mozilla Firefox浏览器。

我将结构改为:

|css |--style.css |data |--albums.json |js |--script.js index.html

这是你的代码:

index.html

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8" />
    <title>JS audio player</title>
    <link rel="stylesheet" type="text/css" href="./css/style.css" />
</head>

<body>
    <table>
        <thead>
            <tr>
                <td>Albums</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Please select an album from the list:</td>
            </tr>
            <tr>
                <td>
                    <select id="album-select" name='Album'>
                        <option></option>
                    </select>
                </td>
            </tr>

        </tbody>
    </table>

    <table id="songs-table">
        <thead>
            <tr>
                <td>Songs</td>
            </tr>
        </thead>
    </table>

    <table id="selected-songs">
        <thead>
            <tr>
                <td>Selected Songs</td>
            </tr>
        </thead>
        <tbody>
            <tr class="title">
                <td></td>
            </tr>
            <tr class="lyrics">
                <td></td>
            </tr>
            <tr>
                <td>
                    <audio id="player" controls='controls'>
                        <source src=''>
                    </audio>
                </td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript" src="./js/script.js"></script>
</body>

</html>

style.css

body {
    width: 1024px;
    height: 100%;
    margin: 0 auto;
}

table {
    float: left;
    width: 33%;
}

thead tr td {
    padding: 10px;
    background-color: lightslategray;
    color: #fff;
    text-align: center;
}

tbody:before {
    content: '-';
    display: block;
    line-height: 20px;
    color: transparent;
}

#songs-table tbody tr {
    cursor: pointer;
}

#songs-table tbody tr:hover {
    background-color: lightgray;
}

albums.json

[
    {
        "title": "Birdsong Small Birds",
        "artist": "BBC",
        "artwork": "Wren",
        "tracks": [
            {
                "title": "Dunnock",
                "mp3": "Birdsong-Dunnock.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }, {
                "title": "Another Dunnock",
                "mp3": "http://www.noiseaddicts.com/samples_1w72b820/272.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }, {
                "title": "Third Dunnock",
                "mp3": "Third-Dunnock.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }
        ]
    },
    {
        "title": "Second Birdsong Birds",
        "artist": "BBC",
        "artwork": "Wren",
        "tracks": [
            {
                "title": "Dunnock in Second",
                "mp3": "Birdsong-Dunnock.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }, {
                "title": "Another Dunnock  in Second",
                "mp3": "http://www.noiseaddicts.com/samples_1w72b820/272.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }, {
                "title": "Third Dunnock  in Second",
                "mp3": "Third-Dunnock.mp3",
                "lyrics": "The Dunnock or hedge sparrow has a fast warbling song often delivered from the top of a hedge or bush"
            }
        ]
    }
]

script.js

window.onload = function () {
    'use strict';

    // Make xhr request to get JSON file
    function getAlbums() {
        var xhttp = new XMLHttpRequest();

        // Detect when response is ready
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState === 4 && xhttp.status === 200) {
                // Parse our response, so we can use it as object
                buildHTML(JSON.parse(xhttp.responseText));
            }
        };

        // Send request
        xhttp.open('GET', './data/albums.json', true);
        xhttp.send();
    }

    // Build page when request comes
    function buildHTML(albums) {
        var albumElement = document.getElementById('album-select'),
            len = albums.length,
            option,
            i;

        for (i = 0; i < len; i++) {
            option = document.createElement('option');
            option.innerHTML = albums[i].title;
            albumElement.add(option);
        }

        albumElement.addEventListener('change', function () {
            var self = this; // Reference self
            albums.forEach(function (album) {
                if (album.title === self.value) {
                    // Pass album object
                    populateSongs(album);
                }
            });
        });
    }

    function populateSongs(album) {
        var songsTable = document.getElementById('songs-table'),
            tbody = document.createElement('tbody'),
            row,
            cell;

        // Add row for each track
        (album.tracks).forEach(function (track) {
            row = tbody.insertRow(0);
            cell = row.insertCell(0);
            cell.innerHTML = track.title;

            cell.addEventListener('click', function () {
                if (this.innerHTML === track.title) {
                    playSong(track);
                }
            });
        });

        // Remove tbody if exist
        Object.keys(songsTable.children).forEach(function (key) {
            if (songsTable.children[key].nodeName === 'TBODY') {
                songsTable.removeChild(songsTable.children[key]);
            }
        });
        songsTable.appendChild(tbody); // Add new tbody
    }

    function playSong(track) {
        var player = document.getElementById('player'),
            selectedSongs = document.getElementById('selected-songs'),
            tbody = selectedSongs.children[1],
            title = tbody.children[0].children[0],
            lyrics = tbody.children[1].children[0];

        title.innerHTML = track.title;
        title.style.fontWeight = 'bold';
        lyrics.innerHTML = track.lyrics;

        // Play song
        player.src = track.mp3;
        player.play();
    }

    getAlbums();
};