AI & MLAdvancedPRJ-103

Speech Emotion Analyzer

Records 3 seconds of your voice and predicts the emotion: happy, sad, angry or neutral.

Built and tested by Shahan Fathima K · Industrial Robotics Institute

Laptop / PC with microphone

Python 3.11, Librosa, NumPy, Scikit-learn, SoundDevice, Trained model file (model.pkl)

LevelAdvanced
Build time3–4 hours (plus model training)
BoardLaptop / PC with microphone
Parts2 components

What is the Speech Emotion Analyzer?

An AI system that recognises emotion from the sound of your voice. It records a short clip from the microphone, extracts MFCC audio features with Librosa, and passes them to a trained machine-learning model that predicts the emotion and how confident it is. You need a trained model file (model.pkl) alongside the script.

How it works

  1. Press Enter and speak for 3 seconds; SoundDevice records the audio.
  2. Librosa normalises the audio and extracts 13 MFCC features (the "fingerprint" of the voice).
  3. The features are averaged into one small vector.
  4. The trained model in model.pkl predicts the emotion.
  5. The emotion and confidence percentage are printed. Type q to quit.

Parts list

ComponentQty
Laptop / Computer1
Microphone (built-in or external)1

Software

  • Python 3.11
  • Librosa
  • NumPy
  • Scikit-learn
  • SoundDevice
  • Trained model file (model.pkl)

How to build the Speech Emotion Analyzer

  1. Install Python 3.11 and tick "Add Python to PATH".
  2. Open a terminal and run: pip install librosa numpy scikit-learn sounddevice
  3. Put the trained model.pkl in the same folder as the script (train one on an emotion dataset such as RAVDESS using the same 13-MFCC features, or get it from IRI).
  4. Paste the code into a new Python file and run it.
  5. Press Enter, speak for 3 seconds, and read the predicted emotion. Type q to quit.

Speech Emotion Analyzer code

Complete, tested Python code for this project. Copy it into Python 3.11 and upload it and run it.

import sounddevice as sd
import numpy as np
import librosa
import pickle

# ======================= Load trained model =======================
try:
    with open("model.pkl", "rb") as file:
        model = pickle.load(file)
    print("Model loaded successfully!")
except Exception:
    print("Error loading model. Check file path.")
    exit()


# ======================= Record audio =======================
def record_audio(duration=3, fs=22050):
    try:
        print("Speak now...")
        audio = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='float32')
        sd.wait()
        print("Recording complete!\n")
        return audio.flatten()
    except Exception as e:
        print("Error recording audio:", e)
        return None


# ======================= Feature extraction =======================
def extract_features(audio, fs=22050):
    try:
        audio = librosa.util.normalize(audio)
        mfcc = librosa.feature.mfcc(y=audio, sr=fs, n_mfcc=13)
        return np.mean(mfcc.T, axis=0)
    except Exception as e:
        print("Error extracting features:", e)
        return None


# ======================= Emotion prediction =======================
def predict_emotion():
    audio = record_audio()
    if audio is None:
        return
    features = extract_features(audio)
    if features is None:
        return
    features = features.reshape(1, -1)

    try:
        prediction = model.predict(features)
        print("Detected Emotion:", prediction[0])
        if hasattr(model, "predict_proba"):
            confidence = np.max(model.predict_proba(features))
            print("Confidence:", round(confidence * 100, 2), "%")
    except Exception as e:
        print("Prediction error:", e)


def main():
    print("=== Emotion Detection System ===")
    while True:
        choice = input("\nPress Enter to record OR type 'q' to quit: ")
        if choice.lower() == 'q':
            print("Exiting... Bye!")
            break
        predict_emotion()


if __name__ == "__main__":
    main()

Real-world uses

  • Call-centre mood analysis
  • Mental health research
  • Smart assistants
  • Learning audio machine learning

Frequently asked questions

What is a Speech Emotion Analyzer?

An AI system that recognises emotion from the sound of your voice. It records a short clip from the microphone, extracts MFCC audio features with Librosa, and passes them to a trained machine-learning model that predicts the emotion and how confident it is.

What components are needed for the Speech Emotion Analyzer?

You need: Laptop / Computer (1), Microphone (built-in or external) (1). Software: Python 3.11, Librosa, NumPy, Scikit-learn, SoundDevice, Trained model file (model.pkl).

Is the Speech Emotion Analyzer project good for beginners?

It is rated advanced and takes about 3–4 hours (plus model training) to build, using the Laptop / PC with microphone. The guide on this page explains every connection and step.

Where can I get the code for the Speech Emotion Analyzer?

The complete, tested Python code is free on this page. Copy it into Python 3.11 and upload it and run it.

Do I need any hardware for the Speech Emotion Analyzer?

No kit is needed. This project runs on a laptop or PC with microphone. For help with the setup, message IRI on WhatsApp at +91 86060 82634.

Industrial Robotics Institute
Logo