Linked Questions

Popular Questions

I would like to add a tag every 15 characters in the text property of SSML. However, the tags all end up at the end of the text.

# Python3
# SSML template / structure
xml_template = ElementTree.Element('speak', version='1.0')
xml_template.set('{}lang', 'ja-JP')
voice = ElementTree.SubElement(xml_template, 'voice')
voice.set('name', 'ja-JP-NanamiNeural')
s = ElementTree.SubElement(voice, 's')
express_as = ElementTree.SubElement(s, 'mstts:express-as')
express_as.set('style', 'cheerful')
prosody = ElementTree.SubElement(express_as, 'prosody')

# Create deep copy of the xml template

print("Enter some text that you want to synthesize, Ctrl-Z to exit")
text = input()

xml_body = deepcopy(xml_template)
prosody = xml_body.find('.//prosody')
prosody.text = ''

# ==============================================================================

# Here's the main part with the issue.
# Add a <bookmark /> element every 15 characters in the SSML text.
def add_bookmarks(text, chunk_length=15):
    chunks = [text[i:i+chunk_length] for i in range(0, len(text), chunk_length)]
    idNum = 1
    for chunk in chunks:
        prosody.text += chunk
        bookmark = ElementTree.SubElement(prosody, 'bookmark')
        bookMarkID = 'bookmark_' + str(idNum)
        idNum += 1

add_bookmarks(text, chunk_length=15)

ssml_string = ElementTree.tostring(xml_body,encoding='unicode',method='xml')

This outputs the following SSML:

<speak version="1.0" xml:lang="ja-JP" xmlns="" xmlns:mstts="" xmlns:emo="">
  <voice name="ja-JP-NanamiNeural">
      <mstts:express-as style="cheerful">
        <prosody pitch="+10.00%" rate="+25.00%">
          Hi, this is a demo text for testing purposes. <bookmark mark="bookmark_1" /><bookmark mark="bookmark_2" /><bookmark mark="bookmark_3" />

Whereas the bookmarks should appear like this:

Hi, this is a d <bookmark mark="bookmark_1" /> emo text for te <bookmark mark="bookmark_2" /> sting purposes. <bookmark mark="bookmark_3" />

Thanks for your help in advance. P.S. It's my first time posting a question on Stack Overflow. Feel free to let me know if there's anything I can do to improve the way I would write a question.

Related Questions