Text To Speech API Drop-In Module (string,part,VoiceId)

I have decided to try out the new Text To Speech API. To do this I wanted to make something very easy to use and understand.
This standalone module contains the documentation example and returns a function that takes a string of text and a part as minimal arguments.

This function can run locally and integrate neatly into your text generation pipeline!

local function splitTextAtPunctuation(text, maxChars)
	local chunks = {}
	local start = 1

	while start <= #text do
		local sub = text:sub(start, math.min(start + maxChars - 1, #text))
		local lastPunct = sub:match(".*()[%.%!%?]") -- Find last period, exclamation, or question mark

		local cutAt = lastPunct or #sub
		table.insert(chunks, text:sub(start, start + cutAt - 1))

		start = start + cutAt
		while text:sub(start, start) == " " do start += 1 end -- Skip spaces
	end

	return chunks
end


return function(text, part, VoiceId, dontplay)
	if text and part then
		local audioTextToSpeech = part:FindFirstChild("AudioTextToSpeech") or Instance.new("AudioTextToSpeech")
		audioTextToSpeech.Parent = part
		audioTextToSpeech.VoiceId = VoiceId or "2"
		audioTextToSpeech.Volume= 1
		audioTextToSpeech.Pitch= part.Parent:GetAttribute("Pitch") or 1
		local deviceOutput = part:FindFirstChild("AudioDeviceOutput") or Instance.new("AudioDeviceOutput")
		deviceOutput.Parent = part

		local wire = part:FindFirstChild("Wire") or Instance.new("Wire")
		wire.Parent = part
		wire.SourceInstance = audioTextToSpeech
		wire.TargetInstance = deviceOutput

		local chunks = splitTextAtPunctuation(text, 300)
		local index = 1
		local connection
		local timer=os.time()
		local function playNext()
			local current=os.time()
			if current-timer<2 then
				task.wait(2)
				timer=os.time()
			end
			if index <= #chunks then
				audioTextToSpeech.Text = chunks[index]
				audioTextToSpeech:Play()
				index += 1
			else
				if connection then
					connection:Disconnect()
					connection = nil
				end
			end
		end

		connection = audioTextToSpeech.Ended:Connect(playNext)

		if not dontplay then
			playNext()
		end

		return audioTextToSpeech
	end
end

RealTime Text To Speech Module-(https://create.roblox.com/store/asset/95338674779280/RealTimeTextToSpeech-Module)
Soon I will be adding it to this open sourced project
[FREE] ROBLOX Mistral 7b AI Chatbot Agent: Aware, Infinite Agents, 2000+ Emojis, 100+ Emotes, Memories, Wikipedia, 32k Context [Open Sourced]
Sources:
AudioTextToSpeech | Documentation - Roblox Creator Hub
[Beta] Text-to-Speech API: From text to voice content instantly

1 Like