Find the Best Parts of a Song to Preview

Published: 2025-10-24

Imagine you have a music streaming service and want to create short audio previews of songs to entice listeners. You want these previews to capture the most engaging parts of each track, such as catchy choruses or instrumental highlights. Getting someone to manually select these segments would be time-consuming and inconsistent. You can’t just pick random sections either, as they might not represent the song well. Ideally, you’d select the choruses or other standout parts that best showcase the song’s appeal. The Audjust API allows you to do exactly that!

In this example, we’ll demonstrate how to use the Audjust API to automatically find the best audio preview segments in a song. These segments can then be used as representative clips for music previews.

Prerequisites

  • An Audjust API key. You can get one for free from the API console (see this guide if you need help).
  • Somewhere or something to run Python code. Since the functionality is exposed via a REST API, you can use any programming language that can make HTTP requests.
  • A song to analyze. Any MP3 file will do.

We’ll use the requests library to make HTTP requests and pydub to handle audio file manipulation. You can install these libraries using pip:

pip install requests pydub

Code

The Audjust API returns a list of preview timestamps in milliseconds. We’ll write a script that uploads an audio file, analyzes it to find preview segments, and then saves those audio files that start a bit before and end a bit after the suggested preview points.

import requests
from pydub import AudioSegment

API_KEY = "YOUR_API_KEY_HERE"  # Replace with your Audjust API key
LOCAL_MP3_PATH = "your_song.mp3"  # Replace with your local mp3 file path


def upload_file(local_path):
    # Step 1: Get upload URLs
    resp = requests.get(
        "https://api.audjust.com/upload", headers={"X-API-Key": API_KEY}
    )
    resp.raise_for_status()
    data = resp.json()
    storage_url = data["storageUrl"]
    retrieval_url = data["retrievalUrl"]

    # Step 2: Upload file to storageUrl
    with open(local_path, "rb") as f:
        put_resp = requests.put(storage_url, data=f)
        put_resp.raise_for_status()
    return retrieval_url


def get_structure_info(source_url):
    resp = requests.post(
        "https://api.audjust.com/structure",
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        json={"sourceFileUrl": source_url},
    )
    resp.raise_for_status()
    return resp.json()


def main():
    # Upload local mp3
    print("Uploading file...")
    source_url = upload_file(LOCAL_MP3_PATH)
    print("Analyzing structure...")
    info = get_structure_info(source_url)
	print("Analysis complete. Finding previews...")

    previews = info.get("previewsMs", [])
    audio = AudioSegment.from_file(LOCAL_MP3_PATH)

    for i, preview in enumerate(previews):
        start_ms = max(0, preview - 5000)  # Start 5 seconds before preview
        end_ms = min(len(audio), preview + 5000)  # End 5 seconds after preview
        out_path = f"preview_{i + 1}.mp3"
        segment = audio[start_ms:end_ms]
        segment.export(out_path, format="mp3")
        print(f"Saved {out_path}")

    if not previews:
        print("No previews found.")


if __name__ == "__main__":
    main()

Try running the script with your own audio file and Audjust API key. The script will output audio files named preview_1.mp3, preview_2.mp3, etc., each containing a 10-second segment centered around the suggested preview points:

$ python makepreviews.py
Uploading file...
Analyzing structure...
Analysis complete. Finding previews...
Saved preview_1.mp3
Saved preview_2.mp3
Saved preview_3.mp3

If you get any errors, make sure your API key is correct, that the audio file path is valid, and that you have enough credits.

You can adjust the preview length by changing the offsets in the start_ms and end_ms calculations. Hopefully this helps you create engaging audio previews for your music application!

More API examples →
Read the API docs →
Try Audjust →