free speech to text code example
Example 1: speech to text
import speech_recognition as sr
def mycommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("listening....")
r.pause_threshold = 1
audio = r.listen(source)
query = mycommand()
print(query)
#prints whatever you said
Example 2: text to speech
import pyttsx3
engine = pyttsx3.init()
engine.say("")
engine.runAndWait()
Example 3: text to speech online
import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# you can use print(voices) to see how many voices you have installed
# print(voices[0].id)
# print(voices[1].id)
# print(voices[2].id)
print(voices)
engine.setProperty('voices', voices[0].id)
def speak(audio):
print(audio)
engine.say(audio)
engine.runAndWait()
speak('Hello')
# prints hello and says it
Example 4: text to speech
import pyttsx3
engine = pyttsx3.init()
engine.say("write here what you want to speak")
engine.runAndWait()
Example 5: text to speech
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
const playButton = document.getElementById('play-button')
const pauseButton = document.getElementById('pause-button')
const stopButton = document.getElementById('stop-button')
const textInput = document.getElementById('text')
const speedInput = document.getElementById('speed')
let currentCharacter
playButton.addEventListener('click', () => {
playText(textInput.value)
})
pauseButton.addEventListener('click', pauseText)
stopButton.addEventListener('click', stopText)
speedInput.addEventListener('input', () => {
stopText()
playText(utterance.text.substring(currentCharacter))
})
const utterance = new SpeechSynthesisUtterance()
utterance.addEventListener('end', () => {
textInput.disabled = false
})
utterance.addEventListener('boundary', e => {
currentCharacter = e.charIndex
})
function playText(text) {
if (speechSynthesis.paused && speechSynthesis.speaking) {
return speechSynthesis.resume()
}
if (speechSynthesis.speaking) return
utterance.text = text
utterance.rate = speedInput.value || 1
textInput.disabled = true
speechSynthesis.speak(utterance)
}
function pauseText() {
if (speechSynthesis.speaking) speechSynthesis.pause()
}
function stopText() {
speechSynthesis.resume()
speechSynthesis.cancel()
}
</script>
<style>
body {
width: 90%;
margin: 0 auto;
margin-top: 1rem;
}
#text {
width: 100%;
height: 50vh;
}
</style>
<script src="script.js" defer></script>
</head>
<body>
<textarea id="text"></textarea>
<label for="speed">Speed</label>
<input type="number" name="spee" id="speed" min=".5" max="3" step=".5" value="1">
<button id="play-button">Play</button>
<button id="pause-button">Pause</button>
<button id="stop-button">Stop</button>
</body>
</html>