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

news2025/3/15 22:57:02

前面有一篇博客说到了讯飞输入法,支持语音输入,也支持电脑内部音源输入,详细参考:【实时语音转文本】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))

控制台输出:
在这里插入图片描述

麦克风语音转文本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端实时语音转文本(麦克风外音&系统内部音源),只需要做一点点设置就行了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/102876.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

CANoe-VN5000接口卡在Network-based模式下典型的应用场景

1、Network-based mode说明 CANoe软硬件都需要设置为Network-based mode 软件从CANoe12版本支持Network-based模式(CANoe12时称为Port-based mode,从13开始改为Network-based mode) 硬件从VN5000系列开始支持Network-based模式,VN5610A和VN5640设备需要确保切换到Network…

必读干货|使用Cmake管理C++项目简明教程

一、背景 Cmake是 kitware公司以及一些开源开发者在开发几个工具套件(VTK)的过程中衍生品,最终形成体系,成为一个独立的开源项目。其官方网站是 cmake.org,可以通过访问官方网站获得更多关于cmake的信息。 它是一个跨平台的编译(Build)工具…

【大数据存储技术】「#3」将数据从Hive导入到MySQL

文章目录准备工作安装Hive、MySQL和SqoopHive预操作启动MySQL、hadoop、hive创建临时表inner_user_log和inner_user_info使用Sqoop将数据从Hive导入MySQL启动hadoop集群、MySQL服务将前面生成的临时表数据从Hive导入到 MySQL 中查看MySQL中user_log或user_info表中的数据准备工…

网页爬虫的本质

1.网页结构分析 提取其中一部分核心介绍 &#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title> </head> <body> <div class"item masonry-brick&quo…

数据管理篇之计算管理

第13章 计算管理 目的&#xff1a;降低计算资源的消耗&#xff0c;提高任务执行的性能&#xff0c;提升任务产出的时间。 1.系统优化 HBO HBO &#xff08;History-Based Optimizer&#xff0c;基于历史的优化&#xff09;是根据任务历史执行情况为任务分配更合理的资源&…

在霍格沃兹测试开发学社学习是种怎样的体验?

霍格沃兹我怎么了解到的 我是河北某二本院校软工专业的学生&#xff0c;大三开始学校来了很多宣讲和实训的公司&#xff0c;都是为我们以后的职业发展做参考。学校有软件测试课程&#xff0c;有一次老师无意提到了霍格沃兹测试开发学社举办的高校“火焰杯”知识竞赛&#xff0…

三角函数sin cos tan和弧度,度等定义及其相关

在此做一个温习及记录&#xff0c;做一个总结&#xff0c;免得到处找。 正弦、余弦和正切是 三角法 里的主要函数&#xff0c;它们是基于一个 直角三角形而建立的。 英文释义&#xff1a; 正弦 &#xff08;sine&#xff09;, 余弦 &#xff08;cosine&#xff09; 和 正切 &a…

毕业设计 单片机心率血氧健康监测手表 - 物联网 嵌入式

文章目录0 前言1 简介2 主要器件3 实现效果4 设计原理4.1 **硬件准备**4.2 **传感器和算法**5 部分核心代码5 最后0 前言 &#x1f525; 这两年开始毕业设计和毕业答辩的要求和难度不断提升&#xff0c;传统的毕设题目缺少创新和亮点&#xff0c;往往达不到毕业答辩的要求&…

VRRP负载均衡模式配置实用吗?

在前面的文章中&#xff0c;我们知道了VRRP单备份组可以快速实现主备切换&#xff08;&#xff09;&#xff0c;轻轻松松将业务中断时间压缩到1秒钟以内&#xff1b;也对比测试了策略路由进行主备切换的过程&#xff08;&#xff09;&#xff0c;虽然能轻松实现主备设备之间的流…

计算机毕业设计php基本微信小程序的贵小团校园社团小程序

项目介绍 随着信息技术和网络技术的飞速发展,人类已进入全新信息化时代,传统管理技术已无法高效,便捷地管理信息。为了迎合时代需求,优化管理效率,各种各样的管理系统应运而生,各行各业相继进入信息管理时代,贵小团校园社团小程序就是信息时代变革中的产物之一。 任何系统都要遵…

计算机毕业设计django基于Python在线酒店管理系统

项目介绍 21世纪的今天,随着社会的不断发展与进步,人们对于信息科学化的认识,已由低层次向高层次发展,由原来的感性认识向理性认识提高,管理工作的重要性已逐渐被人们所认识,科学化的管理,使信息存储达到准确、快速、完善,并能提高工作管理效率,促进其发展。 论文主要是对在线…

Java面试--SpringBoot启动流程

一、SpringBoot是什么 SpringBoot 是依赖于 Spring 的&#xff0c;比起 Spring&#xff0c;除了拥有 Spring 的全部功能以外&#xff0c;SpringBoot 无需繁琐的 Xml 配置&#xff0c;这取决于它自身强大的自动装配功能&#xff1b;并且自身已嵌入Tomcat、Jetty 等 web 容器&am…

C. Another Array Problem(思维)

Problem - C - Codeforces 给你一个有n个整数的数组a。允许你对它进行以下操作&#xff0c;次数不限&#xff08;0次或更多&#xff09;。 选择2个指数i,j&#xff0c;其中1≤i<j≤n&#xff0c;用|ai-aj|替换所有i≤k≤j的ak。 打印最终数组中所有元素的最大和&#xff0c…

TensorFlow之回归模型-1

1 基本概念 回归模型 一个回归模型会生成一个数值类型的预测结果&#xff0c;而一个分类模型会生成一个分类类型的预测结果&#xff0c;例如&#xff0c;如下列举一些回归模型&#xff1a; 一个模型预测一个商品房的价格走向&#xff0c;例如&#xff0c;某个时间点的总体市场…

大一学生《Web编程基础》HTML实例网页代码 HTML+CSS+JS 黑色横排的个人主页作品

&#x1f389;精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 &#x1f482; 作者主页: 【主页——&#x1f680;获取更多优质源码】 &#x1f393; web前端期末大作业…

【MySQL】-事务以及隔离性问题

作者&#xff1a;学Java的冬瓜 博客主页&#xff1a;☀冬瓜的主页&#x1f319; 专栏&#xff1a;【MySQL】 分享&#xff1a;落霞与孤鹜齐飞&#xff0c;秋水共长天一色。——《滕王阁序》 主要内容&#xff1a;事务的概念&#xff0c;代码使用&#xff0c;事务的四大性质、隔…

Shell是运维人员必须掌握的技能

文章目录Shell是运维人员必须掌握的技能Shell、Python 和 Perl1) Perl 语言2) Python 语言3) ShellShell是运维人员必须掌握的技能 Linux 运维人员就是负责 Linux 服务器的运行和维护。随着互联网的爆发&#xff0c;Linux 运维在最近几年也迎来了春天&#xff0c;出现了大量的…

Stm32标准库函数4——BlueTooth采集串口AD数据发送给电脑或者单片机

#include "stm32f10x.h" //在该头文件中默认定义系统时钟为72M #include "delay.h" #include "sys.h" #include "usart.h" #include "adc.h" //将USB转串口模块的Txd引脚电平通过蓝牙模块传送到单片机Rxd&#xff1b;同时…

Linux编辑器-vim的使用

vi/vim的区别简单点来说&#xff0c;它们都是多模式编辑器&#xff0c;不同的是vim是vi的升级版本&#xff0c;它不仅兼容vi的所有指令&#xff0c;而且还有一些新的特性在里面。例如语法加亮&#xff0c;可视化操作不仅可以在终端运行&#xff0c;也可以运行于xwindow、 mac o…

Unity Addressables资源管理 分析器 AnalyzeRule

Addressables资源管理总目录 0.窗口位置 打开的窗口 1.Fixable Rules 可修复的规则 1.1 Check Duplicate Bundle Dependencies 检查重复的Bundle依赖项 此规则通过扫描所有使用BundledAssetGroupSchemas的组&#xff0c; 并投影asset组布局来检查可能冗余的asset。 …