How to Transcribe Audio to Text with AssemblyAI’s Python API – Step‑by‑Step Guide

This tutorial walks you through setting up a Python environment, installing required dependencies, and using AssemblyAI’s high‑accuracy speech‑to‑text Web API to upload audio files, start transcription, and retrieve the transcribed text, including tips for handling API keys and checking transcription status.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Transcribe Audio to Text with AssemblyAI’s Python API – Step‑by‑Step Guide

Recording conversations and converting speech to text automatically is valuable for analysis and downstream tasks. This tutorial demonstrates how to use AssemblyAI’s high‑precision speech‑to‑text Web API to extract text from MP3 recordings (and many other formats).

Prerequisites

Ensure Python 3.6+ is installed. Install the required packages:

requests 2.24.0 – to make HTTP requests to AssemblyAI.

An AssemblyAI account – register at https://app.assemblyai.com/login/ and obtain a free API key.

Set Up a Virtual Environment

Create a virtual environment and activate it:

python3 -m venv ~/venvs/pytranscribe
source ~/venvs/pytranscribe/bin/activate

Install the requests library inside the activated environment:

pip install requests==2.24.0

Upload Audio File

Create upload_audio_file.py with the following code:

import argparse
import os
import requests

API_URL = "https://api.assemblyai.com/v2/"

def upload_file_to_api(filename):
    """Check that the file exists and upload it to AssemblyAI, returning the JSON response."""
    if not os.path.exists(filename):
        return None
    def read_file(filename, chunk_size=5242880):
        with open(filename, 'rb') as _file:
            while True:
                data = _file.read(chunk_size)
                if not data:
                    break
                yield data
    headers = {'authorization': os.getenv('ASSEMBLYAI_KEY')}
    response = requests.post(''.join([API_URL, 'upload']), headers=headers, data=read_file(filename))
    return response.json()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("filename")
    args = parser.parse_args()
    response_json = upload_file_to_api(args.filename)
    if not response_json:
        print("file does not exist")
    else:
        print("File uploaded to URL: {}".format(response_json['upload_url']))

Run the script with the absolute path to your audio file: python upload_audio_file.py /path/to/audio.mp3 The script prints a secure upload URL (e.g., https://cdn.assemblyai.com/upload/…) and a unique file identifier that will be used in the next steps.

Start Transcription

Create initial_transcription.py:

import argparse
import os
import requests

API_URL = "https://api.assemblyai.com/v2/"
CDN_URL = "https://cdn.assemblyai.com/"

def initiate_transcription(file_id):
    """Send a request to start transcribing the uploaded audio file."""
    endpoint = ''.join([API_URL, "transcript"])
    json = {"audio_url": ''.join([CDN_URL, "upload/{}".format(file_id)])}
    headers = {
        "authorization": os.getenv("ASSEMBLYAI_KEY"),
        "content-type": "application/json"
    }
    response = requests.post(endpoint, json=json, headers=headers)
    return response.json()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("file_id")
    args = parser.parse_args()
    print(initiate_transcription(args.file_id))

Run it with the file identifier obtained from the upload step:

python initial_transcription.py 463ce27f-0922-4ea9-9ce4-3353d84b5638

The API returns a JSON object containing a transcription id (e.g., gkuu2krb1-8c7f-4fe3-bb69-6b14a2cac067) and a status of queued.

Retrieve Transcription Result

Create get_transcription.py:

import argparse
import os
import requests

API_URL = "https://api.assemblyai.com/v2/"

def get_transcription(transcription_id):
    """Fetch the transcription JSON from AssemblyAI."""
    endpoint = ''.join([API_URL, "transcript/{}".format(transcription_id)])
    headers = {"authorization": os.getenv('ASSEMBLYAI_KEY')}
    response = requests.get(endpoint, headers=headers)
    return response.json()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("transcription_id")
    args = parser.parse_args()
    resp = get_transcription(args.transcription_id)
    if resp['status'] == "completed":
        for word in resp.get('words', []):
            print(word['text'], end=" ")
    else:
        print("current status of transcription request: {}".format(resp['status']))

Run the script with the transcription ID:

python get_transcription.py gkuu2krb1-8c7f-4fe3-bb69-6b14a2cac067

If the status is queued or processing, the script reports the current state; once the status becomes completed, it prints the full transcribed text.

Next Steps

After obtaining the basic transcription, you can explore advanced features such as supporting additional file formats, transcribing dual‑channel audio, and obtaining speaker labels by consulting the AssemblyAI documentation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAPIspeech-to-textaudio transcriptionAssemblyAI
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.