Check out our demos in our Github repository to see some more code samples.

These code samples are also available on Replit.

Standard synthesis

import asyncio
from lmnt.api import Speech

LMNT_API_KEY = ... # Your API key here
TEXT = 'This is a test of the emergency broadcast system.'

async def main():
  async with Speech(LMNT_API_KEY) as speech:
    voices = await speech.list_voices()
    first_voice = voices[0]['id']
    synthesis = await speech.synthesize(TEXT, first_voice)
    with open('output.wav', 'wb') as f:
      f.write(synthesis['audio'])

if __name__ == '__main__':
  asyncio.run(main())

Streaming synthesis + ChatGPT

import asyncio
from openai import AsyncOpenAI
from argparse import ArgumentParser
from lmnt.api import Speech

LMNT_API_KEY = ... # Your LMNT API key here
OPENAI_API_KEY = ...  # Your OpenAI API key here
MODEL = 'gpt-3.5-turbo'
DEFAULT_PROMPT = 'Give me an inspirational message.'
VOICE_ID = 'mara-wilson'

async def reader_task(conn):
  """Streams audio data from the server and writes it to `output.mp3`."""
  with open('output.mp3', 'wb') as f:
    async for msg in conn:
      f.write(msg['audio'])


async def writer_task(conn, prompt):
    """Streams text from ChatGPT to LMNT."""
    client = AsyncOpenAI(api_key=OPENAI_API_KEY)
    response = await client.chat.completions.create(model=MODEL,
        messages=[{'role': 'user', 'content': prompt}],
        stream=True)

    async for chunk in response:
        if not chunk.choices[0] or not chunk.choices[0].delta or not chunk.choices[0].delta.content:
          continue
        content = chunk.choices[0].delta.content
        await conn.append_text(content)
        print(content, end='', flush=True)

    await conn.finish()


async def main(args):
  s = Speech(LMNT_API_KEY)
  conn = await s.synthesize_streaming(VOICE_ID)

  t1 = asyncio.create_task(reader_task(conn))
  t2 = asyncio.create_task(writer_task(conn, args.prompt))

  await t1
  await t2
  await s.close()


if __name__ == '__main__':
  parser = ArgumentParser()
  parser.add_argument('prompt', default=DEFAULT_PROMPT, nargs='?')
  asyncio.run(main(parser.parse_args()))

Was this page helpful?