
JavaScript 名聲不佳,但它也有自己的優(yōu)勢。也許其中最好的一點是它可以在網(wǎng)頁瀏覽器中運行。如果您使用 Rust 或 Julia 建立程序,則該程式的使用者需要在他或她的 PC 上安裝語言。即使您使用 Docker 將程式及其在該容器中運行所需的所有內(nèi)容容器化,使用者仍然需要安裝 Docker 才能運行它。
但是每個人都有一個網(wǎng)頁瀏覽器。對於像這個小型音訊播放器這樣的簡單程序,JavaScript 的工作效果出奇地好。只需不到 40 行程式碼,並且僅使用 html 文件和 javascript 文件,您就可以建立一個在 Web 瀏覽器中播放音訊的簡單播放器。它很基本,但簡單又優(yōu)雅。它可以播放 .mp3、.wav、.ogg 和其他一些格式。
這是程式碼 - 將第一個檔案儲存為index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Audio Player</title>
<style>
body {
background-color: #a3e4d7; /* Change HEX color */
}
</style>
</head>
<body>
<h1>Simple Audio Player</h1>
<input type="file" id="fileInput" accept="audio/*">
<audio id="audioPlayer" controls>
Your browser does not support the audio element.
</audio>
<button onclick="playAudio()">Play</button>
<button onclick="pauseAudio()">Pause</button>
<script src="script.js"></script>
</body>
</html>
將第二個檔案儲存為 script.js - 將其放在與 index.html 檔案相同的資料夾/目錄中
const audioPlayer = document.getElementById('audioPlayer');
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function() {
const file = this.files[0];
const url = URL.createObjectURL(file);
audioPlayer.src = url;
});
function playAudio() {
audioPlayer.play();
}
function pauseAudio() {
audioPlayer.pause();
}
前往包含兩個檔案的資料夾,然後按一下index.html 檔案- 您的瀏覽器應(yīng)開啟播放器,您將看到用於選擇檔案的框- 從您的電腦中選擇.wav 或.mp3。
注意:index.html 程式碼中有一個地方可以更改播放器視窗的背景顏色 - 嘗試不同的十六進(jìn)位顏色。
本?桑托拉 - 2024 年 10 月
以上是JavaScript 中的簡單音訊播放器的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!