Shorten (or Lengthen) an Audio File

Published: 2025-10-24

Sometimes you may want to change the duration of an audio file, either by shortening it or lengthening it. But just cutting or looping the audio can lead to jarring transitions or unnatural-sounding results. The Audjust API provides a way to intelligently resize audio files by analyzing their structure and generating segments that can be stitched together seamlessly.

In this example, we’ll demonstrate how to use the Audjust API to resize an audio file to a target duration. We’ll upload an audio file, analyze it to extract structural information, and then use the resize API to generate a new list of segments that will adjust the file’s length. Finally, we’ll export the resized audio file.

You will need an Audjust API key to use the API. You can get one for free from the API console. Some basic knowledge of Python is helpful. This code uses the requests library to make HTTP requests. You can install it using pip if you haven’t already:

pip install requests

Example Code

Below is a complete example script that demonstrates how to shorten an audio file to a target length of 60 seconds. Make sure to replace the API_KEY and AUDIO_FILE_PATH variables with your own values.

The example uses polling to check for the results of the analyze and export operations. In a production environment, you might want to set up webhooks to receive notifications when these operations are complete. You need to provide a valid webhook URL in the requests to the analyze and export endpoints. For demonstration purposes, you can use a service like webhook.site to create a temporary webhook URL or use a dummy URL if you prefer polling as shown below.

Because polling can lead to caching issues, we add a random query parameter to the export URL when checking for the final audio file.

import random
import time
import requests

API_KEY = "YOUR_API_KEY"
AUDIO_FILE_PATH = "input.mp3"
EXPORT_FORMAT = "mp3_128"


# 1. Get upload URLs
print("Getting upload URLs...")
upload_resp = requests.get(
    "https://api.audjust.com/upload", headers={"X-API-Key": API_KEY}
)
upload_resp.raise_for_status()
upload_data = upload_resp.json()
storage_url = upload_data["storageUrl"]
retrieval_url = upload_data["retrievalUrl"]

# 2. Upload audio file
print("Uploading audio file...")
with open(AUDIO_FILE_PATH, "rb") as f:
    requests.put(storage_url, data=f)

# 3. Analyze audio
print("Analyzing audio...")
analyze_resp = requests.post(
    "https://api.audjust.com/analyze",
    headers={"X-API-Key": API_KEY},
    json={
        "resultWebhook": "https://example.com/webhook",  # Replace with your webhook URL if needed or use dummy
        "sourceFileUrl": retrieval_url,
    },
)
analyze_result_url = analyze_resp.json()["resultUrl"]

# 4. Poll for analysis result
while True:
    result_resp = requests.get(analyze_result_url)
    if result_resp.status_code == 200 and "result" in result_resp.json():
        analysis = result_resp.json()["result"]
        break
    time.sleep(2)

# 5. Resize to 60 seconds
print("Resizing audio to 60 seconds...")
resize_resp = requests.post(
    "https://api.audjust.com/resize",
    headers={"X-API-Key": API_KEY},
    json={
        "targetLengthSeconds": 60,
        "similarity": analysis["similarity"],
        "boundaries": analysis["boundaries"],
    },
)
resize_result = resize_resp.json()["result"][0]  # Take the first result

# 6. Export resized audio
print("Exporting resized audio...")
export_resp = requests.post(
    "https://api.audjust.com/export",
    headers={"X-API-Key": API_KEY},
    json={
        "resultWebhook": "https://example.com/webhook",  # Replace with your webhook URL if needed or use dummy
        "sourceFileUrl": retrieval_url,
        "exportFormat": EXPORT_FORMAT,
        "segmentsGroups": [resize_result["segmentsSeconds"]],
    },
)
export_url = export_resp.json()["resultUrls"][0]

# 7. Poll for exported audio until available (not 404), use a random parameter to avoid caching
print("Polling for exported audio...")
while True:
    cachebust = random.randint(0, 999999)
    poll_url = f"{export_url}?cb={cachebust}"
    audio_file = requests.get(poll_url)
    if audio_file.status_code != 404:
        with open("output_resized.mp3", "wb") as f:
            f.write(audio_file.content)
        break
    time.sleep(2)

print("Resized audio saved as output_resized.mp3")

When you run the script, you should get output like the following:

Getting upload URLs...
Uploading audio file...
Analyzing audio...
Resizing audio to 60 seconds...
Exporting resized audio...
Resized audio saved as output_resized.mp3

The resulting file output_resized.mp3 will be the resized audio file, shortened (or lengthened) to approximately 60 seconds while maintaining a natural flow and keeping the start and end of the original audio intact.

That’s it! You’ve successfully used the Audjust API to intelligently resize an audio file. You can adjust the targetLengthSeconds parameter in the resize step to change the desired length of the output audio, choose different results (instead of the first one), or change the export format as needed.

There are also other APIs available, please refer to the API documentation for more details on how to use them.

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