> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oyester.metaphy.live/llms.txt
> Use this file to discover all available pages before exploring further.

# Meditation Audio Tool

> Discover and play meditation, ambient, and spiritual audio tracks

# Meditation Audio Tool (`search-meditation-audio`)

Searches for meditation, ambient, and spiritual audio tracks from a curated database, providing direct streaming URLs for immediate playback.

## Overview

The meditation audio tool provides access to a comprehensive collection of high-quality audio tracks specifically designed for meditation, relaxation, and spiritual practices. Each track includes metadata, mood tags, and direct streaming URLs.

## Input Schema

<ParamField body="search" type="string">
  Search term for track title, artist, description, or tags.
</ParamField>

<ParamField body="category" type="string">
  Filter by category: `"meditation"`, `"ambient"`, `"nature-sounds"`.
</ParamField>

<ParamField body="genre" type="string">
  Filter by genre: `"ambient"`, `"meditation"`, `"binaural-beats"`.
</ParamField>

<ParamField body="mood" type="string">
  Filter by mood: `"peaceful"`, `"relaxing"`, `"floating"`, `"dreamy"`.
</ParamField>

<ParamField body="tags" type="string">
  Filter by tags (comma-separated).
</ParamField>

<ParamField body="limit" type="number" default="10">
  Maximum number of tracks to return (max: 20).
</ParamField>

## Output Schema

<ResponseField name="tracks" type="Array">
  Array of audio track objects matching the search criteria.
</ResponseField>

<ResponseField name="tracks[].id" type="string">
  Unique track identifier.
</ResponseField>

<ResponseField name="tracks[].title" type="string">
  Track title.
</ResponseField>

<ResponseField name="tracks[].artist" type="string">
  Artist name.
</ResponseField>

<ResponseField name="tracks[].slug" type="string">
  URL-friendly identifier.
</ResponseField>

<ResponseField name="tracks[].description" type="string">
  Track description.
</ResponseField>

<ResponseField name="tracks[].duration" type="number">
  Duration in seconds.
</ResponseField>

<ResponseField name="tracks[].genre" type="string">
  Music genre.
</ResponseField>

<ResponseField name="tracks[].mood" type="string[]">
  Mood tags.
</ResponseField>

<ResponseField name="tracks[].tags" type="string[]">
  Additional tags.
</ResponseField>

<ResponseField name="tracks[].category" type="string">
  Content category.
</ResponseField>

<ResponseField name="tracks[].audioUrl" type="string">
  Direct audio file URL for streaming.
</ResponseField>

<ResponseField name="tracks[].thumbnailUrl" type="string">
  Thumbnail image URL.
</ResponseField>

<ResponseField name="tracks[].bpm" type="number">
  Beats per minute (if applicable).
</ResponseField>

<ResponseField name="totalFound" type="number">
  Number of tracks returned.
</ResponseField>

<ResponseField name="searchCriteria" type="object">
  Echo of search parameters used.
</ResponseField>

<ResponseField name="message" type="string">
  Human-readable result summary.
</ResponseField>

## Example Usage

### Search for Ambient Meditation

```json theme={null}
{
  "toolCallId": "call_audio_123",
  "toolName": "search-meditation-audio",
  "args": {
    "search": "ambient meditation",
    "mood": "peaceful",
    "limit": 5
  }
}
```

### Tool Result

```json theme={null}
{
  "tracks": [
    {
      "id": "track-123",
      "title": "Sow",
      "artist": "Harbours & Oceans",
      "slug": "sow-harbours-oceans",
      "description": "A floating, relaxing ambient track perfect for meditation and peaceful moments.",
      "duration": 196,
      "genre": "Ambient",
      "mood": ["Floating", "Relaxing"],
      "tags": ["ambient", "floating", "relaxing", "meditation"],
      "category": "meditation",
      "audioUrl": "https://audiocdn.epidemicsound.com/lqmp3/01HW80ZP3ZJV1ZEN48W8AAVK75.mp3",
      "bpm": 52
    }
  ],
  "totalFound": 1,
  "searchCriteria": {
    "search": "ambient meditation",
    "mood": "peaceful",
    "limit": 5
  },
  "message": "Found 1 meditation audio track"
}
```

## Natural Language Triggers

The tool responds to various audio-related queries:

* "Play some ambient music for meditation"
* "Find relaxing sounds for mindfulness"
* "Play meditation music"
* "Find peaceful audio tracks"
* "Play binaural beats for focus"
* "Find nature sounds for relaxation"

## Integration Examples

### Meditation Audio Player

```javascript theme={null}
class MeditationAudioPlayer {
  constructor() {
    this.currentTrack = null;
    this.audioElement = new Audio();
    this.playlist = [];
    this.isPlaying = false;

    this.initializePlayer();
  }

  initializePlayer() {
    this.audioElement.addEventListener('loadedmetadata', () => {
      console.log(`Duration: ${this.audioElement.duration} seconds`);
      this.updateDurationDisplay();
    });

    this.audioElement.addEventListener('timeupdate', () => {
      this.updateProgress();
    });

    this.audioElement.addEventListener('ended', () => {
      this.playNextTrack();
    });

    this.audioElement.addEventListener('play', () => {
      this.isPlaying = true;
      this.updatePlayButton();
    });

    this.audioElement.addEventListener('pause', () => {
      this.isPlaying = false;
      this.updatePlayButton();
    });
  }

  async loadTracks(searchCriteria) {
    const response = await chat.sendMessage(
      `Find meditation audio tracks for ${searchCriteria.mood || 'relaxation'}`,
      'friend'
    );

    const toolResults = response.toolResults || [];
    const audioResult = toolResults.find(r => r.toolName === 'search-meditation-audio');

    if (audioResult) {
      this.playlist = audioResult.result.tracks;
      this.renderPlaylist();
      return audioResult.result;
    }

    return { tracks: [], totalFound: 0 };
  }

  playTrack(track) {
    this.currentTrack = track;
    this.audioElement.src = track.audioUrl;
    this.audioElement.play();

    this.updatePlayerUI(track);
  }

  pauseTrack() {
    this.audioElement.pause();
  }

  resumeTrack() {
    this.audioElement.play();
  }

  playNextTrack() {
    if (this.playlist.length === 0) return;

    const currentIndex = this.currentTrack ?
      this.playlist.findIndex(t => t.id === this.currentTrack.id) : -1;

    const nextIndex = (currentIndex + 1) % this.playlist.length;
    this.playTrack(this.playlist[nextIndex]);
  }

  playPreviousTrack() {
    if (this.playlist.length === 0) return;

    const currentIndex = this.currentTrack ?
      this.playlist.findIndex(t => t.id === this.currentTrack.id) : -1;

    const prevIndex = currentIndex <= 0 ? this.playlist.length - 1 : currentIndex - 1;
    this.playTrack(this.playlist[prevIndex]);
  }

  setVolume(volume) {
    this.audioElement.volume = Math.max(0, Math.min(1, volume));
  }

  seekTo(time) {
    this.audioElement.currentTime = time;
  }

  renderPlaylist() {
    const playlistHTML = this.playlist.map(track => `
      <div class="track-item ${this.currentTrack?.id === track.id ? 'playing' : ''}"
           onclick="player.playTrack(${JSON.stringify(track).replace(/"/g, '&quot;')})">
        <div class="track-info">
          <h4>${track.title}</h4>
          <p>${track.artist}</p>
          <span class="duration">${this.formatDuration(track.duration)}</span>
        </div>
        <div class="track-tags">
          ${track.tags?.map(tag => `<span class="tag">${tag}</span>`).join('') || ''}
        </div>
      </div>
    `).join('');

    document.getElementById('playlist').innerHTML = playlistHTML;
  }

  updatePlayerUI(track) {
    document.getElementById('current-track-title').textContent = track.title;
    document.getElementById('current-track-artist').textContent = track.artist;
    document.getElementById('current-track-description').textContent = track.description || '';

    // Update background or theme based on mood
    this.updateTheme(track.mood);
  }

  updateTheme(mood) {
    const body = document.body;
    body.className = ''; // Clear existing classes

    if (mood && mood.length > 0) {
      const primaryMood = mood[0].toLowerCase();
      body.classList.add(`theme-${primaryMood}`);
    }
  }

  updateProgress() {
    const progress = (this.audioElement.currentTime / this.audioElement.duration) * 100;
    document.getElementById('progress-bar').style.width = `${progress}%`;
    document.getElementById('current-time').textContent = this.formatTime(this.audioElement.currentTime);
  }

  updateDurationDisplay() {
    document.getElementById('total-time').textContent = this.formatTime(this.audioElement.duration);
  }

  updatePlayButton() {
    const playBtn = document.getElementById('play-btn');
    playBtn.textContent = this.isPlaying ? '⏸️' : '▶️';
  }

  formatTime(seconds) {
    if (!seconds || !isFinite(seconds)) return '0:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }

  formatDuration(seconds) {
    if (!seconds) return '';
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  }
}

// Global player instance
const player = new MeditationAudioPlayer();

// Load and play meditation tracks
async function startMeditationSession(mood = 'peaceful') {
  const results = await player.loadTracks({ mood });

  if (results.tracks.length > 0) {
    player.playTrack(results.tracks[0]);
    console.log(`Starting ${mood} meditation session`);
  }
}
```

## Best Practices

<Tip>
  **Progressive Loading**: Load metadata first, then full audio for better performance.
</Tip>

<Tip>
  **Caching**: Cache frequently played tracks locally for offline access.
</Tip>

<Tip>
  **Mood Matching**: Match audio mood to user's current state and meditation goals.
</Tip>

<Tip>
  **Seamless Playback**: Implement gapless playback for continuous meditation sessions.
</Tip>

## Error Handling

```javascript theme={null}
async function playMeditationAudioWithFallback(trackId) {
  try {
    const track = await getTrackById(trackId);
    if (!track) throw new Error('Track not found');

    // Try to play the track
    await player.playTrack(track);

  } catch (error) {
    console.warn('Primary audio failed, trying fallback');

    // Try alternative audio sources
    const fallbackTrack = await findSimilarTrack(trackId);
    if (fallbackTrack) {
      await player.playTrack(fallbackTrack);
    } else {
      // Play local meditation timer or ambient sounds
      playLocalMeditationAudio();
    }
  }
}
```

## Use Cases

* **Guided Meditation**: Background music for meditation sessions
* **Ambient Soundscapes**: Create peaceful environments for mindfulness
* **Focus Enhancement**: Binaural beats and concentration audio
* **Sleep Aid**: Relaxation tracks for better sleep
* **Stress Relief**: Calming audio for anxiety reduction
* **Creative Sessions**: Ambient music for creative thinking and flow states
