Prerequisite You should have an API key from AssemblyAI and have it stored in a .env file.

Introduction

This guide demonstrates how to transcribe a local audio file using the AssemblyAI API. You’ll learn how to set up your environment, configure your API key, and transcribe an audio file stored on your local machine.

Setup

Step 1: Install Required Packages

First, install the necessary packages using pip:

pip install python-dotenv assemblyai

Step 2: Create a .env File

Create a .env file in the project root with your AssemblyAI API key:

ASSEMBLYAI_API_KEY=your_assemblyai_api_key

Transcribing a Local Audio File

Step 3: Create the Python Script

Create a Python script named assemblyai-local-transcription.py with the following content:

assemblyai-local-transcription.py
import os
from dotenv import load_dotenv
import assemblyai as aai

# Load environment variables from .env file
load_dotenv()

# Get AssemblyAI API key from environment variables
aai.settings.api_key = os.getenv('ASSEMBLYAI_API_KEY')

# Initialize the transcriber
transcriber = aai.Transcriber()

# Define the local audio file path
local_audio_file_path = "downloads/voice.m4a"  # Ensure this path is correct and the file exists

# Set the transcription configuration
config = aai.TranscriptionConfig(speaker_labels=True)

try:
    # Transcribe the local audio file
    transcript = transcriber.transcribe(local_audio_file_path, config)

    # Print the transcription text and ID
    print(transcript.text)
    print(transcript.id)

    # Print the speaker labels and their corresponding text
    for utterance in transcript.utterances:
        print(f"Speaker {utterance.speaker}: {utterance.text}")

except FileNotFoundError as e:
    print(f"File not found: {e.filename}")

except Exception as e:
    print(f"An error occurred: {str(e)}")

Step 4: Run the Script

Ensure you have the .env file in the same directory as the script. Then, execute the script:

python assemblyai-local-transcription.py

Conclusion

You have successfully transcribed a local audio file using the AssemblyAI API! This guide provided a basic example to get you started. You can now expand on this by customizing the transcription configuration and handling different audio files stored locally.