簡體   English   中英

HTML 和 javascript 音頻播放器

[英]HTML and javascript audio player

我正在使用 javascript 而沒有 jquery 在 HTML 中創建音頻播放器。 我這樣做是為了讓它與此類似例子 我將第一個表格作為下拉列表,我將選擇其中一個專輯,相應的歌曲將顯示在下一個窗格中,這部分一切正常。 我的問題是我不知道如何對其進行編碼,以便當我單擊中間窗格中的歌曲時,該歌曲將與相應的圖像、專輯名稱和歌曲名稱一起顯示在最后一個窗格中。

這是我的代碼,其中包含我的 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>

任何幫助將不勝感激。

首先:

  • 你的 HTML 結構很糟糕而且不正確
  • 不要寫內聯css
  • 試着理解你寫的代碼

我沒有太多時間查看所有代碼。 希望這會幫助你。 一些代碼行被注釋,如果有什么不清楚的就問。

您將需要某種類型的本地服務器,因為您不能對本地文件使用 xhr 請求。 如果您安裝了 python,則可以從項目的根目錄使用python -m SimpleHTTPServer 3001 ,然后導航到127.0.0.1:3001 (或本地主機)。 或者您可以使用 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();
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM