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.
Show me the code
assemblyai-local-transcription.py
Copy
import osfrom dotenv import load_dotenvimport assemblyai as aai# Load environment variables from .env fileload_dotenv()# Get AssemblyAI API key from environment variablesaai.settings.api_key = os.getenv('ASSEMBLYAI_API_KEY')# Initialize the transcribertranscriber = aai.Transcriber()# Define the local audio file pathlocal_audio_file_path = "downloads/voice.m4a" # Ensure this path is correct and the file exists# Set the transcription configurationconfig = 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)}")
Create a Python script named assemblyai-local-transcription.py with the following content:
assemblyai-local-transcription.py
Copy
import osfrom dotenv import load_dotenvimport assemblyai as aai# Load environment variables from .env fileload_dotenv()# Get AssemblyAI API key from environment variablesaai.settings.api_key = os.getenv('ASSEMBLYAI_API_KEY')# Initialize the transcribertranscriber = aai.Transcriber()# Define the local audio file pathlocal_audio_file_path = "downloads/voice.m4a" # Ensure this path is correct and the file exists# Set the transcription configurationconfig = 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)}")
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.