當前位置: 首頁>>代碼示例>>Python>>正文


Python gtts.gTTS方法代碼示例

本文整理匯總了Python中gtts.gTTS方法的典型用法代碼示例。如果您正苦於以下問題:Python gtts.gTTS方法的具體用法?Python gtts.gTTS怎麽用?Python gtts.gTTS使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gtts的用法示例。


在下文中一共展示了gtts.gTTS方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: doFileStuff

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def doFileStuff(line,isSlow):
    myobj = gTTS(text=line, lang='en', slow=isSlow) 
    myobj.save("placeholder.mp3")
    
    y, sr = librosa.load("placeholder.mp3")
    data = librosa.resample(y, sr, SAMPLE_RATE)
    librosa.output.write_wav('placeholder.wav', data, SAMPLE_RATE)
    d, sr = sf.read('placeholder.wav')
    sf.write('placeholder.wav', d, sr)

    y, sr = librosa.load("placeholder.mp3")
    lowData = librosa.resample(y, sr, SAMPLE_RATE*LOW_FACTOR)
    librosa.output.write_wav('lowPlaceholder.wav', lowData, SAMPLE_RATE)
    d, sr = sf.read('lowPlaceholder.wav')
    sf.write('lowPlaceholder.wav', d, sr)

    return data 
開發者ID:carykh,項目名稱:rapLyrics,代碼行數:19,代碼來源:rapSpeaker.py

示例2: validate_lang

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    """
    if ctx.params['nocheck']:
        return lang

    try:
        if lang not in tts_langs():
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
開發者ID:luoliyan,項目名稱:chinese-support-redux,代碼行數:25,代碼來源:cli.py

示例3: notify

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def notify(self, notification):
        if notification == "":
                notification = "No+Notification+Data+Recieved"
        
        mp3 = MP3_CACHE_DIR + "/" + notification.replace("+","_") + ".mp3"
        text = notification.replace("+"," ")

        if not os.path.isfile(mp3) :
            print("Generating MP3...")
            tts = gTTS(text=text, lang='en-uk') # See Google TTS API for more Languages (Note: This may do translation Also - Needs Testing)
            tts.save(mp3)
        else:
            print("Reusing MP3...")

        print("Sending notification...")
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Pull IP Address for Local HTTP File Serving (Note: This requires an internet connection)
        s.connect(("8.8.8.8", 80))
        ip_add = s.getsockname()[0]
        print (ip_add)
        s.close()
        self.Cast(ip_add, mp3)

        print("Notification Sent.")

        return 
開發者ID:GhostBassist,項目名稱:GooglePyNotify,代碼行數:27,代碼來源:GooglePyNotify.py

示例4: __init__

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def __init__(self, *commands, key=None, use_yandex=True, prefixes=None, strict=False):
        """Answers with audio message of user's text"""

        if not commands:
            commands = ("скажи", "произнеси")

        super().__init__(*commands, prefixes=prefixes, strict=strict)

        self.key = key
        self.providers = [(lambda text, lang, key=None: gTTS(text=text, lang=lang)),
            (lambda text, lang, key=None: yTTS(text=text, lang=lang, key=key)),]

        if use_yandex:
            self.providers[0], self.providers[1] = self.providers[1], self.providers[0]

        example = self.command_example()
        self.description = [f"Текст в речь",
            f"{example} [текст] - произнести текст (+ значит ударение перед ударной гласной)."] 
開發者ID:ekonda,項目名稱:sketal,代碼行數:20,代碼來源:outsource_sayer.py

示例5: say

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def say(text):
        print("%s" % text)
        if isinstance(text, str):
            text = text.decode("utf-8")
        md5 = hashlib.md5(text.encode('utf-8')).hexdigest()
        fname = "/tmp/%s.mp3" % md5
        if not os.path.exists(fname):
            myre = re.compile('[[A-Za-z]', re.UNICODE)
            lang = 'en' if myre.match(text) else 'ru'

            logging.getLogger('requests').setLevel(logging.getLogger('').getEffectiveLevel())
            tts = gtts.gTTS(text=text, lang=lang, slow=False)
            tts.save(fname)

        with open(os.devnull, 'w') as fnull:
            subprocess.call("mplayer %s" % fname, shell=True, stderr=fnull, stdout=fnull) 
開發者ID:undera,項目名稱:pylgbst,代碼行數:18,代碼來源:__init__.py

示例6: _generate_audio_file

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def _generate_audio_file(self):
        """
        Generic method used as a Callback in TTSModule
            - must provided the audio file and write it on the disk

        .. raises:: FailToLoadSoundFile
        """

        # Since the gTTS lib disabled the SSL verification we get rid of insecure request warning
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        
        tts = gTTS(text=self.words, lang=self.language)
        
        # OK we get the audio we can write the sound file
        tts.save(self.file_path)
        
        # Re enable the warnings to avoid affecting the whole kalliope process 
        warnings.resetwarnings() 
開發者ID:kalliope-project,項目名稱:kalliope,代碼行數:20,代碼來源:googletts.py

示例7: textPlay

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def textPlay():
    f = open("output.txt", "r")

    text = f.read()


    # Language in which you want to convert
    language = 'en'

    # Passing the text and language to the engine, 
    # here we have marked slow=False. Which tells 
    # the module that the converted audio should 
    # have a high speed
    myobj = gTTS(text=text, lang=language, slow=False)
    myobj.save("welcome.wav")
    '''
    print('Playing')
    winsound.PlaySound("This is real this is me",winsound.SND_FILENAME)
    pygame.init()
    t= pygame.mixer.Sound("welcome.wav")
    t.play()'''

    os.system("start welcome.wav") 
開發者ID:ishita27,項目名稱:Printed-Text-recognition-and-conversion,代碼行數:25,代碼來源:text2speech.py

示例8: tts

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def tts(bot: Bot, update: Update, args):
    current_time = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S")
    filename = datetime.now().strftime("%d%m%y-%H%M%S%f")
    reply = " ".join(args)
    update.message.chat.send_action(ChatAction.RECORD_AUDIO)
    lang="ml"
    tts = gTTS(reply, lang)
    tts.save("k.mp3")
    with open("k.mp3", "rb") as f:
        linelist = list(f)
        linecount = len(linelist)
    if linecount == 1:
        update.message.chat.send_action(ChatAction.RECORD_AUDIO)
        lang = "en"
        tts = gTTS(reply, lang)
        tts.save("k.mp3")
    with open("k.mp3", "rb") as speech:
        update.message.reply_voice(speech, quote=False) 
開發者ID:TGExplore,項目名稱:Marie-2.0-English,代碼行數:20,代碼來源:tts.py

示例9: validate_lang

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    Uses <tld> to fetch languages from other domains
    """
    if ctx.params['nocheck']:
        return lang

    try:
        tld = ctx.params['tld']
        if lang not in tts_langs(tld):
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
開發者ID:pndurette,項目名稱:gTTS,代碼行數:27,代碼來源:cli.py

示例10: __init__

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def __init__(self, language="en-us"):
        self._language = language
        self._tts = gTTS(lang=self._language, text="dummy")

    # public methods 
開發者ID:HoussemCharf,項目名稱:FunUtils,代碼行數:7,代碼來源:tts.py

示例11: speak

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def speak(text):
    from gtts import gTTS
    import os
    tts = gTTS(text=text, lang='ko')
    tts.save("tmp_talk.mp3")
    os.system("omxplayer tmp_talk.mp3")
    os.system("rm -f tmp_talk.mp3") 
開發者ID:jeonghoonkang,項目名稱:BerePi,代碼行數:9,代碼來源:sample.py

示例12: text_to_speech_online

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def text_to_speech_online(text, lang='en'):
    """Convert text to speech using Google Translate’s and save in mp3. Need an internet connection.

    Args:
        text (str): Text.
        lang (str): Language (Ex: pt-br).

    """
    tts = gTTS(text=text, lang=lang)
    tts.save("sound.mp3") 
開發者ID:lucasayres,項目名稱:python-tools,代碼行數:12,代碼來源:text_to_speech_online.py

示例13: tts_save

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def tts_save(filename, text, lang):
	# run_command(["pico2wave", "--wave", filename, "-l", "en-GB", text])
	try:
		tts = gTTS(text=text, lang=lang)
		tts.save(filename)
	except AttributeError:
		raise UserError("Whoops. Looks like gtts is broken right now.")
	except (RecursionError, requests.exceptions.HTTPError):
		raise UserError("There was a problem converting that via gtts")
	except AssertionError as e:
		if e.args and e.args[0] == "No text to send to TTS API":
			raise UserError("I can't convert that to TTS. Looks like there's not much there.")
		else:
			raise 
開發者ID:mdiller,項目名稱:MangoByte,代碼行數:16,代碼來源:clip.py

示例14: text_to_speech

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def text_to_speech(self, speech):
        speech = remove_ansi_escape_seq(speech)
        tts = gTTS(speech, lang="en")
        tts.save("voice.mp3")
        audio = AudioSegment.from_mp3('voice.mp3')
        playback.play(audio)
        os.remove("voice.mp3") 
開發者ID:sukeesh,項目名稱:Jarvis,代碼行數:9,代碼來源:voice.py

示例15: get_google

# 需要導入模塊: import gtts [as 別名]
# 或者: from gtts import gTTS [as 別名]
def get_google(self):
        tts = gTTS(self.text, lang=self.lang)
        tts.save(self.path) 
開發者ID:luoliyan,項目名稱:chinese-support-redux,代碼行數:5,代碼來源:tts.py


注:本文中的gtts.gTTS方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。