【Google语音转文字】Speech to Text 超级好用的语音转文本API

这篇具有很好参考价值的文章主要介绍了【Google语音转文字】Speech to Text 超级好用的语音转文本API。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前面有一篇博客说到了讯飞输入法,支持语音输入,也支持电脑内部音源输入,详细参考:【实时语音转文本】PC端实时语音转文本(麦克风外音&系统内部音源)

但是它只是作为一个工具来使用,如果我们想自己做一些好玩的东西,比如通过语音来控制电脑做一些自动化的操作等,我们先要收集语音转换为文本,然后再通过解析文本来操作平台,那我们就需要获取到语音识别的内容,通过讯飞输入法这种就不能办到了,这时候我们需要使用API来处理,通过对比国内外一些大厂的智能语音API,发现还是Google的API更加【智能】,更加【听得懂人话】。

说明:因为是使用了Google的API,所以需要具备一定的网络环境,需要能访问Google。

准备工作

官方文档:Cloud Speech-to-Text>文档>准备工作

根据官方文档一步步设置就行了,这里简单说明以下流程:

  • 设置Google Cloud 项目
  • 确保有一个结算账号关联到该项目
  • 启用 Speech-to-Text API
  • 创建新的服务账号
  • 创建JSON密钥
  • 设置身份验证环境变量

语音文件转文本Python示例

准备python环境安装依赖:

  • google-cloud-speech==2.16.2
  • pyaudio==0.2.12
  • six==1.16.0

if __name__ == "__main__":
    # Imports the Google Cloud client library
    from google.cloud import speech

    import os
    os.environ["http_proxy"] = "http://127.0.0.1:7890"
    os.environ["https_proxy"] = "http://127.0.0.1:7890"

    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "xxxxx.json"

    # Instantiates a client
    client = speech.SpeechClient()

    # The name of the audio file to transcribe
    gcs_uri = "gs://cloud-samples-data/speech/brooklyn_bridge.raw"

    audio = speech.RecognitionAudio(uri=gcs_uri)

    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code="en-US",
    )

    # Detects speech in the audio file
    response = client.recognize(config=config, audio=audio)

    for result in response.results:
        print("Transcript: {}".format(result.alternatives[0].transcript))

控制台输出:
google cloud speech-to-text,自由飞翔,语音识别,python,人工智能,speech-to-text

麦克风语音转文本Python示例

准备python环境安装依赖:

  • google-cloud-speech==2.16.2
  • pyaudio==0.2.12
  • six==1.16.0
#!/usr/bin/env python

from __future__ import division

import re
import sys

from google.cloud import speech

import pyaudio
from six.moves import queue

import os
os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "xxxx.json"

# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms


class MicrophoneStream(object):
    """Opens a recording stream as a generator yielding the audio chunks."""

    def __init__(self, rate, chunk):
        self._rate = rate
        self._chunk = chunk

        # Create a thread-safe buffer of audio data
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            # The API currently only supports 1-channel (mono) audio
            # https://goo.gl/z757pE
            channels=1,
            rate=self._rate,
            input=True,
            frames_per_buffer=self._chunk,
            # Run the audio stream asynchronously to fill the buffer object.
            # This is necessary so that the input device's buffer doesn't
            # overflow while the calling thread makes network requests, etc.
            stream_callback=self._fill_buffer,
        )

        self.closed = False

        return self

    def __exit__(self, type, value, traceback):
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)
        self._audio_interface.terminate()

    def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
        """Continuously collect data from the audio stream, into the buffer."""
        self._buff.put(in_data)
        return None, pyaudio.paContinue

    def generator(self):
        while not self.closed:
            # Use a blocking get() to ensure there's at least one chunk of
            # data, and stop iteration if the chunk is None, indicating the
            # end of the audio stream.
            chunk = self._buff.get()
            if chunk is None:
                return
            data = [chunk]

            # Now consume whatever other data's still buffered.
            while True:
                try:
                    chunk = self._buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break

            yield b"".join(data)


def listen_print_loop(responses):
    """Iterates through server responses and prints them.

    The responses passed is a generator that will block until a response
    is provided by the server.

    Each response may contain multiple results, and each result may contain
    multiple alternatives; for details, see https://goo.gl/tjCPAU.  Here we
    print only the transcription for the top alternative of the top result.

    In this case, responses are provided for interim results as well. If the
    response is an interim one, print a line feed at the end of it, to allow
    the next result to overwrite it, until the response is a final one. For the
    final one, print a newline to preserve the finalized transcription.
    """
    num_chars_printed = 0
    for response in responses:
        if not response.results:
            continue

        # The `results` list is consecutive. For streaming, we only care about
        # the first result being considered, since once it's `is_final`, it
        # moves on to considering the next utterance.
        result = response.results[0]
        if not result.alternatives:
            continue

        # Display the transcription of the top alternative.
        transcript = result.alternatives[0].transcript

        # Display interim results, but with a carriage return at the end of the
        # line, so subsequent lines will overwrite them.
        #
        # If the previous result was longer than this one, we need to print
        # some extra spaces to overwrite the previous result
        overwrite_chars = " " * (num_chars_printed - len(transcript))

        if not result.is_final:
            sys.stdout.write(transcript + overwrite_chars + "\r")
            sys.stdout.flush()

            num_chars_printed = len(transcript)

        else:
            print(transcript + overwrite_chars)

            # Exit recognition if any of the transcribed phrases could be
            # one of our keywords.
            if re.search(r"\b(exit|quit)\b", transcript, re.I):
                print("Exiting..")
                break

            num_chars_printed = 0


def main():
    # See http://g.co/cloud/speech/docs/languages
    # for a list of supported languages.
    language_code = "zh"  # a BCP-47 language tag

    client = speech.SpeechClient()
    config = speech.RecognitionConfig(
        encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=RATE,
        language_code=language_code,
    )

    streaming_config = speech.StreamingRecognitionConfig(
        config=config, interim_results=True
    )

    with MicrophoneStream(RATE, CHUNK) as stream:
        audio_generator = stream.generator()
        requests = (
            speech.StreamingRecognizeRequest(audio_content=content)
            for content in audio_generator
        )

        responses = client.streaming_recognize(streaming_config, requests)

        # Now, put the transcription responses to use.
        listen_print_loop(responses)


if __name__ == "__main__":
    main()

通过麦克风语音会实时转为文本输出,如果需要再对结果进行处理,可以在listen_print_loop方法中修改。

以上代码是在官网的示例基础上做了修改:

  • 设置代理(国内需要设置http_proxy代理,否则无法访问到google api)
  • 设置环境变量GOOGLE_APPLICATION_CREDENTIALS,正常情况是在客户端系统设置里设置,这里测试可以直接用代码设置环境变量,这个参数就是准备工作中的JSON密钥文件
  • 设置语言language_code为中文zh,官方支持的语言列表:Speech-to-Text 支持的语言

其他官方示例

Google Cloud 官方示例

Speech-to-Text 示例

电脑内部语音

同样可以将麦克风设置为系统音源,这样就可以实时将电脑内的视频、语音转为文本,做个实时字幕工具也是不错的。具体操作方法参考【实时语音转文本】PC端实时语音转文本(麦克风外音&系统内部音源),只需要做一点点设置就行了。文章来源地址https://www.toymoban.com/news/detail-783773.html

到了这里,关于【Google语音转文字】Speech to Text 超级好用的语音转文本API的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 文本内容转换成语音播放的工具:Speech Mac

    Speech Mac版是一款适用于Mac电脑的语音合成工具 。它将macOS语音合成器的所有功能整合到一个易于使用的界面中。通过Speech Mac版,用户可以选择40多种声音和语言,方便地将文本转换为语音。用户可以将文本拖放或粘贴到Speech中,并随时更改语音和语速。此外,单击一个单词即

    2024年02月05日
    浏览(21)
  • 前端开发中基于Web Speech API(speechSynthesis接口)实现文字转语音功能

    一、Web Speech 的概念及用法 在开发业务系统时,有时候可能需要使用语音播报一段文字。 目前文字转语音即语音合成技术现在已经很成熟了,像百度、讯飞等都提供了相关的服务,支持将文字转换成各种形式的语音,通常这些服务都需要付费使用,如果对语音要求不高,并且

    2024年01月24日
    浏览(23)
  • 【Microsoft Azure 的1024种玩法】五十五.Azure speech service之通过JavaScript快速实现文本转换为语音

    文本转语音可使用语音合成标记语言 (SSML) 将输入文本转换为类似人类的合成语音,本篇文档主要介绍了如何通过JavaScript 的语音SDK实现文本转换为语音的实践操作 【Microsoft Azure 的1024种玩法】一.一分钟快速上手搭建宝塔管理面板 【Microsoft Azure 的1024种玩法】二.基于Azure云平

    2024年02月09日
    浏览(19)
  • 请问哪些好用文字转语音软件?

    好用的文字转语音软件给大家推荐UU在线工具,这里你可以自由调节语速、音调、音量以及发音人。播放合成的语音,将音频导出到本地就可以了。 缺点就是生成的音质比较单一,只能选择四款发音人,无法添加音乐、添加间隔等等。 想要应对复杂的配音环境,给大家推荐知

    2024年02月14日
    浏览(15)
  • 深度学习神经网络学习笔记-多模态方向-11-Deep Voice: Real-time Neural Text-to-Speech

    本文提出Deep Voice,一种完全由深度神经网络构建的生产质量文本到语音系统。Deep Voice为真正的端到端神经语音合成奠定了基础。该系统由五个主要的构建模块组成:用于定位音素边界的分割模型、字素到音素的转换模型、音素时长预测模型、基频预测模型和音频合成模型。对

    2024年02月06日
    浏览(22)
  • 一款非常好用的语音转文字工具介绍

    最近发现一款非常好用的语音转文字的工具Whisper,支持将视频和语音转换成文字,同时记录语音的位置信息,支持语言的翻译,可以将英文转换成中文。同时支持实时的语音自动采集录制。 下面是下载的地址: 【免费】视频、语音转文字Windows版资源-CSDN文库 大家下载好文件

    2024年02月02日
    浏览(26)
  • 【离线文本转语音文件】java spring boot jacob实现文字转语音文件,离线文本转化语音,中英文生成语音,文字朗读,中文生成声音,文字生成声音文件,文字转语音文件,文字变声音。

    输入文字(支持中英文),点击转换生成***.wav文件,点击下载到本地就可。  生成后的音频文件播放,时长1分8秒          这次采用jacob实现,相比百度AI需要联网,本项目定位内网环境实现。所以最终采jacob。 1.环境配置: 本次采用版本jacob-1.19,我们需要下载jacob.jar和dll

    2024年02月16日
    浏览(38)
  • 论文阅读:VITS2: Improving Quality and Efficiency of Single-Stage Text-to-Speech with Adversarial

    论文标题是“ VITS2: Improving Quality and Efficiency of Single-Stage Text-to-Speech with Adversarial Learning and Architecture Design ”,写不下了,是2023.7.31原vits团队刚刚挂在arxiv上的文章,主要基于四个方面对vits做了改动,此篇文章我们就不讲vits,主要分析vits2的部分。 单阶段文本到语音模型最近

    2024年02月07日
    浏览(20)
  • Python GUI设计——Entry文本框、文字区域Text

    目录 1.Entry 1.1基本概念 1.2使用show参数隐藏输入的字符 1.3Entry的get()方法 1.4Entry的insert()方法 1.5Entry的delete()方法 1.6计算数学表达式使用eval() 2.文字区域Text 2.1基本概念 2.2插入文字insert() 2.3Text加上滚动条Scrollbar设计 2.4字形 2.4.1family 2.4.2weight 2.4.3size 2.5选取文字 2.6Text的索引 2.

    2024年01月18日
    浏览(18)
  • whisper 语音识别AI 声音To文字

    Whisper  是一个由 OpenAI 训练并开源的神经网络,功能是语音识别,能把 语音 转换为 文字 ,在英语语音识别方面的稳健性和准确性接近人类水平。 1、Whisper支持语音转录和翻译两项功能并接受各种语音格式,模型中、英、法、德、意、日等主流语言上取得85%以上的准确率,完全

    2024年02月08日
    浏览(22)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包