Text to Speech in Emacs Without Any Package

;;; my-read-aloud.el --- Read text aloud in buffer
;; Copyright (C) 2025 Raoul Comninos
;; Author: Raoul Comninos
;; Keywords: 
;;; Code:

(defvar read-aloud-process nil
  "Variable to store the current reading process.")

(defun read-aloud-from-cursor ()
  "Read aloud from the cursor position or selected text using eSpeak."
  (interactive)
  (let ((text (if (use-region-p)
                  (buffer-substring-no-properties (region-beginning) (region-end))
                (buffer-substring-no-properties (point) (point-max)))))
    (message "Text: %s" text)
    (when (and read-aloud-process (process-live-p read-aloud-process))
      (kill-process read-aloud-process))
    (setq read-aloud-process (start-process "espeak-process" nil "/usr/bin/espeak" text))))

(defun stop-reading-aloud ()
  "Stop the current reading process."
  (interactive)
  (when (and read-aloud-process (process-live-p read-aloud-process))
    (kill-process read-aloud-process)
    (setq read-aloud-process nil)))

(defvar my/reading-aloud nil "Flag to track whether reading aloud is active.")

(defun my/toggle-read-aloud ()
  "Toggle reading aloud from the cursor position."
  (interactive)
  (if my/reading-aloud
      (progn
  (stop-reading-aloud)
  (setq my/reading-aloud nil))
    (progn
      (read-aloud-from-cursor)
      (setq my/reading-aloud t))))

(global-set-key (kbd "<f9>") 'my/toggle-read-aloud)

;;; my-read-aloud.el ends here

Return to Home