Audio Player Card

Embed and play audio content directly on your page with this compact, self-contained audio player card.

This component uses the native HTML5 element but replaces its default browser controls with a custom, consistently styled interface built with CSS and JavaScript. It's perfect for podcast episodes, song previews, or audio notes.

Screenshot of a compact audio player card with custom play and progress controls.

Get Source Code Preview

About this Component

This is a functional component that uses vanilla JavaScript to hook into the HTML5 audio element's API. It provides a clean, custom interface for common audio playback functions. These include play/pause, viewing progress, and seeking to a specific point in the track by clicking on the progress bar.

Features

Code Breakdown

HTML Structure

The card is a div that contains all the visible elements, like the play button and progress bar. A notable part of the structure is the actual audio element at the end, which has the browser's default controls attribute removed so it is not visible. This element is the engine of the player, and the custom controls will interact with it via JavaScript. The play/pause state is tracked with a data-playing attribute on the main card.

CSS Styling

The CSS is mainly responsible for the layout and appearance of the custom controls. The most interesting part is how the play and pause icons are swapped. Both SVG icons are present in the HTML. The data-playing attribute on the parent card is used as a CSS hook. By default, the pause icon is hidden. When the attribute changes to data-playing="true", the CSS rules .audio-player-card[data-playing="true"] .ap-icon-play { display: none; } and .audio-player-card[data-playing="true"] .ap-icon-pause { display: block; } are activated, swapping which icon is visible.

JavaScript Logic

The script uses querySelector to find all the necessary elements (the audio element, button, progress bar, etc.). It then adds event listeners to manage playback:

  1. An event listener on the playBtn toggles the audio.play() and audio.pause() methods.
  2. Listeners on the audio element for play and pause events update the data-playing attribute on the card, which triggers the CSS icon swap.
  3. A timeupdate listener on the audio element fires repeatedly as the track plays. It's used to update the width of the progress bar and the current time display.
  4. A click listener on the progressContainer calculates the click position and updates the audio.currentTime property to allow the user to seek through the track.

Code

Here is the complete, self-contained code. To use it, simply change the src attribute of the source element within the audio tag to point to your own audio file.

View Output