Skip to main content

Overview

SoundWave supports multiple playback modes including YouTube audio streaming and Spotify embedded player. Each mode offers unique features and controls for an optimal listening experience.

Player Modes

YouTube Audio Player

Stream audio directly from YouTube with automatic source fallback

Spotify Embedded Player

Play Spotify tracks using the official embedded player

Enabling Autoplay

Modern browsers require user interaction before allowing autoplay. SoundWave handles this automatically:
// Autoplay is enabled after any user interaction
document.addEventListener('click', enableAutoplay, { once: true });

function enableAutoplay() {
    console.log('Interacción del usuario detectada. La reproducción automática está habilitada.');
}
This listener fires only once and enables autoplay for the entire session.

YouTube Audio Playback

Selecting a Track

When you click on a search result, SoundWave fetches audio sources:
itemElement.addEventListener('click', function () {
    if (isSuggestion) {
        // If it's a suggestion, fill the search field
        document.getElementById('song-name').value = item.title;
        suggestionsContainer.style.display = 'none';
        sourceLinksContainer.innerHTML = '';
        fetchSearchResults(item.title);
    } else {
        // If it's a result, select the song
        selectedVideoId = item.videoId;
        selectedTitle = item.title;
        stopAudioPlayer();
        clearSourceLinks();
        fetchSourceCode(selectedVideoId);
    }
});

Fetching Audio Sources

SoundWave extracts audio URLs from YouTube pages:
1

Fetch Video Page

The system fetches the YouTube watch page with listen=1 parameter for audio-optimized content.
2

Parse Audio Elements

Extract <source> and <audio> elements containing audio URLs.
3

Verify Accessibility

Check each URL to ensure it’s accessible before presenting to the user.
4

Begin Playback

Automatically play the first accessible audio source.
function fetchSourceCode(videoId, groupIndex = currentGroupIndex, resultIndex = 0) {
    const watchUrl = `https://yewtu.be/watch?v=${videoId}&listen=1`;
    const allOriginsUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(watchUrl)}`;

    fetch(allOriginsUrl)
        .then(response => {
            if (response.ok) return response.text();
            throw new Error('Network response was not ok.');
        })
        .then(data => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(data, 'text/html');
            const sourceElements = doc.querySelectorAll('source[src]');
            const audioElements = doc.querySelectorAll('audio[src]');

            // Get all audio links
            const sourceLinks = Array.from(sourceElements).map(source => source.src);
            const audioLinks = Array.from(audioElements).map(audio => audio.src);
            const allLinks = [...sourceLinks, ...audioLinks];

            // Verify link accessibility
            checkAccessibleLinks(allLinks, videoId, groupIndex, resultIndex);
        })
        .catch(error => {
            console.error('Error fetching source code:', error);
            sourceLinksContainer.textContent = 'No se pudo cargar el código fuente.';
            findNextVideo(groupIndex, resultIndex);
        });
}
The listen=1 parameter optimizes the page for audio-only playback, reducing bandwidth usage.

Audio Element Control

The HTML5 audio player provides standard controls:
<audio id="audio-player" controls>
    <source src="audio-url-here" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>
If no accessible audio sources are found, SoundWave automatically tries the next video in the search results.

Spotify Playback

Embedded Player

Spotify tracks play using the official embedded player:
function playTrack(embedUrl) {
    const player = document.getElementById('player');
    player.src = embedUrl; // Update iframe src with new URL
}

Player Configuration

The Spotify player iframe is configured with optimal settings:
<iframe
    id="player"
    style="border-radius:12px;"
    width="100%"
    height="152"
    frameBorder="0"
    allowfullscreen=""
    allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
    loading="lazy"
    src="">
</iframe>
const embedUrl = `https://open.spotify.com/embed/track/${track.id}?utm_source=generator&theme=0`;
The theme parameter is set to 0 for dark mode to match SoundWave’s interface.

Playback Controls

Stopping Playback

Stop the current audio playback:
function stopAudioPlayer() {
    const audioPlayer = document.getElementById('audio-player');
    if (audioPlayer) {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
    }
}

Clearing Audio Sources

Remove all audio source links:
function clearSourceLinks() {
    sourceLinksContainer.innerHTML = '';
}

Download Mode

SoundWave also includes a download workflow for Spotify tracks:
1

Enter Spotify URL

Paste a Spotify track URL in the input field.
2

Generate Download Link

The system converts the Spotify URL to a downloadable audio link.
3

Play or Download

Use the audio player to preview or download the track.
document.getElementById('spotifyForm').addEventListener('submit', async function (event) {
    event.preventDefault();

    const spotifyUrl = document.getElementById('spotifyUrl').value;
    const audioPlayer = document.getElementById('audioPlayer');

    try {
        const response = await fetch('https://jsnode-ab0e.onrender.com/get-download-link', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ spotifyUrl })
        });

        const data = await response.json();

        if (response.ok) {
            // Display download link
            result.innerHTML = `<p>Download Link: <a href="${data.downloadLink}" target="_blank">${data.downloadLink}</a></p>`;

            // Configure audio player
            audioPlayer.src = data.downloadLink;
            audioPlayer.style.display = 'block';
            audioPlayer.play();
        }
    } catch (error) {
        console.error('An error occurred:', error);
    }
});

Playback Features

Auto-fallback

Automatically tries next video if current one fails

Source Verification

Verifies audio URLs before playback

Multi-format Support

Supports multiple audio formats and sources

Troubleshooting

No Audio Sources Found

If no audio sources are available:
  1. The system automatically tries the next video in results
  2. Check your internet connection
  3. Try a different search query

Playback Interrupted

Some audio sources may have geographical restrictions or temporary unavailability. The auto-fallback feature helps mitigate this.

Browser Compatibility

SoundWave works best on modern browsers that support:
  • HTML5 audio elements
  • ES6 JavaScript features
  • Fetch API
  • DOMParser

Best Practices

  1. Wait for Full Page Load: Allow autoplay to be enabled before selecting tracks
  2. Use Headphones: For the best audio quality experience
  3. Check Volume: Adjust your system volume before playback
  4. Stable Connection: Ensure a stable internet connection for uninterrupted streaming

Next Steps

Search Guide

Learn advanced search techniques

Filtering Results

Understand how results are filtered

Build docs developers (and LLMs) love