使用 JavaScript 訪問音訊檔案中的元資料


音訊檔案通常包含曲目標題、表演者姓名、專輯名稱、流派和出版年份作為嵌入的元資料。這些資料可能對媒體播放器、音樂庫和編目工具等應用程式很有用。可以透過多種方式在 JavaScript 中訪問這些元資料,特別是藉助 jsmediatags 和 music-metadata-browser 等庫,本文的目標是演示在 JavaScript 程式語言中用於從音訊檔案中檢索元資料的幾種技術。

訪問音訊元資料的方法

使用 HTML5 音訊元素

HTML5 音訊元素提供了一種簡單的方法來載入和與瀏覽器中的音訊檔案進行互動,但是,它僅提供對有限元資料的訪問,這主要與播放時間資料有關。

音訊元素不提供對 ID3 標籤(例如,標題、藝術家)的直接訪問。為此,通常需要一個專用的庫。

示例程式碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Metadata Display</title>
</head>

<body>
    <h1>Audio Metadata</h1>
    <!-- Audio element for the audio file -->
    <audio id="audioElement" controls>
            <source src=
"https://samplelib.com/lib/preview/mp3/sample-3s.mp3" 
                    type="audio/mp3">
            Your browser does not support the audio element.
        </audio>

    <!-- Container to display metadata -->
    <div id="metadata">
        <p id="duration">Duration: Loading...</p>
    </div>

    <script>
        // JavaScript to access metadata when audio is loaded
        const audioElement = document.getElementById("audioElement");

        // Event listener for when metadata is loaded
        audioElement.addEventListener("loadedmetadata", () => {
            // Access and display duration
            const duration = audioElement.duration;
            document.getElementById("duration").textContent = `Duration: ${duration.toFixed(2)} seconds`;
        });
    </script>
</body>

</html>

輸出


使用 Web 音訊 API

Web 音訊 API 能夠管理音訊處理,它不能直接幫助提取元資料,但是,它可以用來訪問諸如持續時間、音訊緩衝區資訊等屬性。

與音訊元素一樣,Web 音訊 API 無法直接訪問 ID3 標籤,它主要提供音訊解碼和操作功能。

示例程式碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Audio Duration Display</title>
</head>

<body>
    <h1>Audio Duration</h1>

    <!-- Button to load the audio file -->
    <button id="loadAudioButton">Load Audio File</button>

    <!-- Display container for the duration -->
    <p id="durationDisplay">Duration: Not loaded yet</p>

    <script>
        // Initialize AudioContext
        const audioContext = new(window.AudioContext || window.webkitAudioContext)();

        // Function to fetch and decode audio
        async function loadAudio() {
            try {
                // Fetch the audio file
                const response = await fetch("gasolina.mp3");
                const arrayBuffer = await response.arrayBuffer();

                // Decode audio data
                const decodedData = await audioContext.decodeAudioData(arrayBuffer);

                // Display duration on the webpage
                document.getElementById("durationDisplay").textContent = `Duration: ${decodedData.duration.toFixed(2)} seconds`;
            } catch (error) {
                console.error("Error decoding audio:", error);
                document.getElementById("durationDisplay").textContent = "Error loading audio.";
            }
        }

        // Attach event to button to load audio
        document.getElementById("loadAudioButton").addEventListener("click", loadAudio);
    </script>
</body>

</html>

輸出


使用 ID3 庫 (ID3.js)

像 ID3.js 這樣的 ID3 庫允許從 MP3 檔案中全面提取元資料,這些庫解析 ID3 標籤並提供對元資料的訪問,例如標題、藝術家和專輯。

使用 ID3.js

要使用 ID3.js,您必須在專案中包含該庫,然後可以透過將檔案作為 Blob 或 File 物件傳遞來讀取元資料。

  • **步驟 1:**透過 CDN 包含 ID3.js 或透過 npm 安裝它
這種方法可以對 ID3 標籤中提供的各種元資料屬性進行直接訪問。

示例程式碼

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Audio Duration Display</title>
</head>

<body>
    <h1>Audio Duration Display</h1>

    <!-- File input for audio upload -->
    <input type="file" id="audioFile" accept="audio/*">

    <!-- Display area for duration -->
    <p id="durationDisplay">Duration: Not available</p>

    <script>
        const fileInput = document.getElementById("audioFile");

        fileInput.addEventListener("change", async (event) => {
            const file = event.target.files[0];

            if (file) {
                try {
                    // Initialize AudioContext
                    const audioContext = new(window.AudioContext || window.webkitAudioContext)();

                    // Read the file as an ArrayBuffer
                    const arrayBuffer = await file.arrayBuffer();

                    // Decode audio data
                    const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

                    // Display duration on the webpage
                    document.getElementById("durationDisplay").textContent = `Duration: ${audioBuffer.duration.toFixed(2)} seconds`;
                } catch (error) {
                    console.error("Error decoding audio:", error);
                    document.getElementById("durationDisplay").textContent = "Error loading audio duration.";
                }
            }
        });
    </script>
</body>

</html>

輸出


更新於: 2024年11月6日

202 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告