最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python語音識別API實(shí)現(xiàn)文字轉(zhuǎn)語音的幾種方法

 更新時間:2022年03月17日 16:09:13   作者:小鋒學(xué)長生活大爆炸  
本文主要介紹了Python語音識別API實(shí)現(xiàn)文字轉(zhuǎn)語音的幾種方法,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價值,感興趣的小伙伴們可以參考一下

搜狗(目前好用,免費(fèi))

    def textToAudio_Sougou(message, filePath):
        # https://ai.so    gou.com/doc/?url=/docs/content/tts/references/rest/ 
        '''
        curl -X POST \
             -H "Content-Type: application/json" \
             --data '{
          "appid": "xxx",
          "appkey": "xxx",
          "exp": "3600s"
        }' https://api.zhiyin.sogou.com/apis/auth/v1/create_token
        '''
 
        token = 'xxx'
        headers = { 
            'Authorization' : 'Bearer '+token,
            'Appid' : 'xxx',
            'Content-Type' : 'application/json',
            'appkey' : 'xxx',
            'secretkey' : 'xxx'
        }
        data = {
          'input': {
            'text': message
          },
          'config': {
            'audio_config': {
              'audio_encoding': 'LINEAR16',
              'pitch': 1.0,
              'volume': 1.0,
              'speaking_rate': 1.0
            },
            'voice_config': {
              'language_code': 'zh-cmn-Hans-CN',
              'speaker': 'female'
            }
          }
        }
        
        result = requests.post(url=url, headers=headers, data=json.dumps(data, ensure_ascii=False).encode('utf-8')).content
        with open(filePath, 'wb') as f:
            f.write(result)

百度(現(xiàn)在收費(fèi)了,送一定額度)

import base64
import json
import os
import time
import shutil
import requests

class BaiduVoiceToTxt():
? ? # 初始化函數(shù)
? ? def __init__(self):
? ? ? ? # 定義要進(jìn)行切割的pcm文件的位置。speech-vad-demo固定好的,沒的選
? ? ? ? self.pcm_path = ".\\speech-vad-demo\\pcm\\16k_1.pcm"
? ? ? ? # 定義pcm文件被切割后,分割成的文件輸出到的目錄。speech-vad-demo固定好的,沒的選
? ? ? ? self.output_pcm_path = ".\\speech-vad-demo\\output_pcm\\"

? ? # 百度AI接口只接受pcm格式,所以需要轉(zhuǎn)換格式
? ? # 此函數(shù)用于將要識別的mp3文件轉(zhuǎn)換成pcm格式,并輸出為.\speech-vad-demo\pcm\16k_1.pcm
? ? def change_file_format(self,filepath):
? ? ? ? file_name = filepath
? ? ? ? # 如果.\speech-vad-demo\pcm\16k_1.pcm文件已存在,則先將其刪除
? ? ? ? if os.path.isfile(f"{self.pcm_path}"):
? ? ? ? ? ? os.remove(f"{self.pcm_path}")
? ? ? ? # 調(diào)用系統(tǒng)命令,將文件轉(zhuǎn)換成pcm格式,并輸出為.\speech-vad-demo\pcm\16k_1.pcm
? ? ? ? change_file_format_command = f".\\ffmpeg\\bin\\ffmpeg.exe -y ?-i {file_name} ?-acodec pcm_s16le -f s16le -ac 1 -ar 16000 {self.pcm_path}"
? ? ? ? os.system(change_file_format_command)

? ? # 百度AI接口最長只接受60秒的音視,所以需要切割
? ? # 此函數(shù)用于將.\speech-vad-demo\pcm\16k_1.pcm切割
? ? def devide_video(self):
? ? ? ? # 如果切割輸出目錄.\speech-vad-demo\output_pcm\已存在,那其中很可能已有文件,先將其清空
? ? ? ? # 清空目錄的文件是先刪除,再創(chuàng)建
? ? ? ? if os.path.isdir(f"{self.output_pcm_path}"):
? ? ? ? ? ? shutil.rmtree(f"{self.output_pcm_path}")
? ? ? ? time.sleep(1)
? ? ? ? os.mkdir(f"{self.output_pcm_path}")
? ? ? ? # vad-demo.exe使用相對路徑.\pcm和.\output_pcm,所以先要將當(dāng)前工作目錄切換到.\speech-vad-demo下不然vad-demo.exe找不到文件
? ? ? ? os.chdir(".\\speech-vad-demo\\")
? ? ? ? # 直接執(zhí)行.\vad-demo.exe,其默認(rèn)會將.\pcm\16k_1.pcm文件切割并輸出到.\output_pcm目錄下
? ? ? ? devide_video_command = ".\\vad-demo.exe"
? ? ? ? os.system(devide_video_command)
? ? ? ? # 切換回工作目錄
? ? ? ? os.chdir("..\\")

? ? # 此函數(shù)用于將.\speech-vad-demo\output_pcm\下的文件的文件名的時間格式化成0:00:00,000形式
? ? def format_time(self, msecs):
? ? ? ? # 一個小時毫秒數(shù)
? ? ? ? hour_msecs = 60 * 60 * 1000
? ? ? ? # 一分鐘對應(yīng)毫秒數(shù)
? ? ? ? minute_msecs = 60 * 1000
? ? ? ? # 一秒鐘對應(yīng)毫秒數(shù)
? ? ? ? second_msecs = 1000
? ? ? ? # 文件名的時間是毫秒需要先轉(zhuǎn)成秒。+500是為了四舍五入,//是整除
? ? ? ? # msecs = (msecs + 500) // 1000
? ? ? ? # 小時
? ? ? ? hour = msecs // hour_msecs
? ? ? ? if hour < 10:
? ? ? ? ? ? hour = f"0{hour}"
? ? ? ? # 扣除小時后剩余毫秒數(shù)
? ? ? ? hour_left_msecs = msecs % hour_msecs
? ? ? ? # 分鐘
? ? ? ? minute = hour_left_msecs // minute_msecs
? ? ? ? # 如果不足10分鐘那在其前補(bǔ)0湊成兩位數(shù)格式
? ? ? ? if minute < 10:
? ? ? ? ? ? minute = f"0{minute}"
? ? ? ? # 扣除分鐘后剩余毫秒數(shù)
? ? ? ? minute_left_msecs = hour_left_msecs % minute_msecs
? ? ? ? # 秒
? ? ? ? second = minute_left_msecs // second_msecs
? ? ? ? # 如果秒數(shù)不足10秒,一樣在其前補(bǔ)0湊足兩位數(shù)格式
? ? ? ? if second < 10:
? ? ? ? ? ? second = f"0{second}"
? ? ? ? # 扣除秒后剩余毫秒數(shù)
? ? ? ? second_left_msecs = minute_left_msecs % second_msecs
? ? ? ? # 如果不足10毫秒或100毫秒,在其前補(bǔ)0湊足三位數(shù)格式
? ? ? ? if second_left_msecs < 10:
? ? ? ? ? ? second_left_msecs = f"00{second_left_msecs}"
? ? ? ? elif second_left_msecs < 100:
? ? ? ? ? ? second_left_msecs = f"0{second_left_msecs}"
? ? ? ? # 格式化成00:00:00,000形式,并返回
? ? ? ? time_format = f"{hour}:{minute}:{second},{second_left_msecs}"
? ? ? ? return time_format

? ? # 此函數(shù)用于申請?jiān)L問ai接口的access_token
? ? def get_access_token(self):
? ? ? ? # 此變量賦值成自己API Key的值
? ? ? ? client_id = 'f3wT23Otc8jXlDZ4HGtS4jfT'
? ? ? ? # 此變量賦值成自己Secret Key的值
? ? ? ? client_secret = 'YPPjW3E0VGPUOfZwhjNGVn7LTu3hwssj'
? ? ? ? auth_url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret

? ? ? ? response_at = requests.get(auth_url)
? ? ? ? # 以json格式讀取響應(yīng)結(jié)果
? ? ? ? json_result = json.loads(response_at.text)
? ? ? ? # 獲取access_token
? ? ? ? access_token = json_result['access_token']
? ? ? ? return access_token

? ? # 此函數(shù)用于將.\speech-vad-demo\output_pcm\下的單個文件由語音轉(zhuǎn)成文件
? ? def transfer_voice_to_srt(self,access_token,filepath):
? ? ? ? # 百度語音識別接口
? ? ? ? url_voice_ident = "http://vop.baidu.com/server_api"
? ? ? ? # 接口規(guī)范,以json格式post數(shù)據(jù)
? ? ? ? headers = {
? ? ? ? ? ? 'Content-Type': 'application/json'
? ? ? ? }
? ? ? ? # 打開pcm文件并讀取文件內(nèi)容
? ? ? ? pcm_obj = open(filepath,'rb')
? ? ? ? pcm_content_base64 = base64.b64encode(pcm_obj.read())
? ? ? ? pcm_obj.close()
? ? ? ? # 獲取pcm文件大小
? ? ? ? pcm_content_len = os.path.getsize(filepath)

? ? ? ? # 接口規(guī)范,則體函義見官方文件,值得注意的是cuid和speech兩個參數(shù)的寫法
? ? ? ? post_data = {
? ? ? ? ? ? "format": "pcm",
? ? ? ? ? ? "rate": 16000,
? ? ? ? ? ? "dev_pid": 1737,
? ? ? ? ? ? "channel": 1,
? ? ? ? ? ? "token": access_token,
? ? ? ? ? ? "cuid": "1111111111",
? ? ? ? ? ? "len": pcm_content_len,
? ? ? ? ? ? "speech": pcm_content_base64.decode(),
? ? ? ? }
? ? ? ? proxies = {
? ? ? ? ? ? 'http':"127.0.0.1:8080"
? ? ? ? }
? ? ? ? # 調(diào)用接口,進(jìn)行音文轉(zhuǎn)換
? ? ? ? response = requests.post(url_voice_ident, headers=headers, data=json.dumps(post_data))
? ? ? ? # response = requests.post(url_voice_ident,headers=headers,data=json.dumps(post_data),proxies=proxies)
? ? ? ? return response.text

if __name__ == "__main__":
? ? # 實(shí)例化
? ? baidu_voice_to_srt_obj = BaiduVoiceToTxt()
? ? # 自己要進(jìn)行音文轉(zhuǎn)換的音視存放的文件夾
? ? video_dir = ".\\video\\"
? ? all_video_file =[]
? ? all_file = os.listdir(video_dir)
? ? subtitle_format = "{\\fscx75\\fscy75}"
? ? # 只接受.mp3格式文件。因?yàn)槠渌袷經(jīng)]研究怎么轉(zhuǎn)成pcm才是符合接口要求的
? ? for filename in all_file:
? ? ? ? if ".mp3" in filename:
? ? ? ? ? ? all_video_file.append(filename)
? ? all_video_file.sort()
? ? i = 0
? ? video_file_num = len(all_video_file)
? ? print(f"當(dāng)前共有{video_file_num}個音頻文件需要轉(zhuǎn)換,即將進(jìn)行處理請稍等...")
? ? # 此層for循環(huán)是逐個mp3文件進(jìn)行處理
? ? for video_file_name in all_video_file:
? ? ? ? i += 1
? ? ? ? print(f"當(dāng)前轉(zhuǎn)換{video_file_name}({i}/{video_file_num})")
? ? ? ? # 將音視翻譯成的內(nèi)容輸出到同目錄下同名.txt文件中
? ? ? ? video_file_srt_path = f".\\video\\{video_file_name[:-4]}.srt"
? ? ? ? # 以覆蓋形式打開.txt文件
? ? ? ? video_file_srt_obj = open(video_file_srt_path,'w+')

? ? ? ? filepath = os.path.join(video_dir, video_file_name)
? ? ? ? # 調(diào)用change_file_format將mp3轉(zhuǎn)成pcm格式
? ? ? ? baidu_voice_to_srt_obj.change_file_format(filepath)
? ? ? ? # 將轉(zhuǎn)換成的pcm文件切割成多個小于60秒的pcm文件
? ? ? ? baidu_voice_to_srt_obj.devide_video()
? ? ? ? # 獲取token
? ? ? ? access_token = baidu_voice_to_srt_obj.get_access_token()
? ? ? ? # 獲取.\speech-vad-demo\output_pcm\目錄下的文件列表
? ? ? ? file_dir = baidu_voice_to_srt_obj.output_pcm_path
? ? ? ? all_pcm_file = os.listdir(file_dir)
? ? ? ? all_pcm_file.sort()
? ? ? ? j = 0
? ? ? ? pcm_file_num = len(all_pcm_file)
? ? ? ? print(f"當(dāng)前所轉(zhuǎn)文件{video_file_name}({i}/{video_file_num})被切分成{pcm_file_num}塊,即將逐塊進(jìn)行音文轉(zhuǎn)換請稍等...")
? ? ? ? # 此層for是將.\speech-vad-demo\output_pcm\目錄下的所有文件逐個進(jìn)行音文轉(zhuǎn)換
? ? ? ? for filename in all_pcm_file:
? ? ? ? ? ? j += 1
? ? ? ? ? ? filepath = os.path.join(file_dir, filename)
? ? ? ? ? ? if (os.path.isfile(filepath)):
? ? ? ? ? ? ? ? # 獲取文件名上的時間
? ? ? ? ? ? ? ? time_str = filename[10:-6]
? ? ? ? ? ? ? ? time_str_dict = time_str.split("-")
? ? ? ? ? ? ? ? time_start_str = baidu_voice_to_srt_obj.format_time(int(time_str_dict[0]))
? ? ? ? ? ? ? ? time_end_str = baidu_voice_to_srt_obj.format_time(int(time_str_dict[1]))
? ? ? ? ? ? ? ? print(f"當(dāng)前轉(zhuǎn)換{video_file_name}({i}/{video_file_num})-{time_start_str}-{time_end_str}({j}/{pcm_file_num})")
? ? ? ? ? ? ? ? response_text = baidu_voice_to_srt_obj.transfer_voice_to_srt(access_token, filepath)
? ? ? ? ? ? ? ? # 以json形式讀取返回結(jié)果
? ? ? ? ? ? ? ? json_result = json.loads(response_text)
? ? ? ? ? ? ? ? # 將音文轉(zhuǎn)換結(jié)果寫入.srt文件
? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"{j}\r\n")
? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"{time_start_str} --> {time_end_str}\r\n")
? ? ? ? ? ? ? ? if json_result['err_no'] == 0:
? ? ? ? ? ? ? ? ? ? print(f"{time_start_str}-{time_end_str}({j}/{pcm_file_num})轉(zhuǎn)換成功:{json_result['result'][0]}")
? ? ? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"{subtitle_format}{json_result['result'][0]}\r\n")
? ? ? ? ? ? ? ? elif json_result['err_no'] == 3301:
? ? ? ? ? ? ? ? ? ? print(f"{time_start_str}-{time_end_str}({j}/{pcm_file_num})音頻質(zhì)量過差無法識別")
? ? ? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"{subtitle_format}音頻質(zhì)量過差無法識別\r\n")
? ? ? ? ? ? ? ? else:
? ? ? ? ? ? ? ? ? ? print(f"{time_start_str}-{time_end_str}({j}/{pcm_file_num})轉(zhuǎn)換過程遇到其他錯誤")
? ? ? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"{subtitle_format}轉(zhuǎn)換過程遇到其他錯誤\r\n")
? ? ? ? ? ? ? ? video_file_srt_obj.writelines(f"\r\n")
? ? ? ? video_file_srt_obj.close()

騰訊(收費(fèi)的)

到此這篇關(guān)于Python語音識別API實(shí)現(xiàn)文字轉(zhuǎn)語音的幾種方法的文章就介紹到這了,更多相關(guān)Python 文字轉(zhuǎn)語音內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談keras的深度模型訓(xùn)練過程及結(jié)果記錄方式

    淺談keras的深度模型訓(xùn)練過程及結(jié)果記錄方式

    今天小編就為大家分享一篇淺談keras的深度模型訓(xùn)練過程及結(jié)果記錄方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • SQLAlchemy的主要組件詳細(xì)講解

    SQLAlchemy的主要組件詳細(xì)講解

    SQLAlchemy是一個基于Python實(shí)現(xiàn)的ORM框架,能滿足大多數(shù)數(shù)據(jù)庫操作需求,同時支持多種數(shù)據(jù)庫引擎(SQLite,MySQL,Postgresql,Oracle等),這篇文章主要介紹了SQLAlchemy的主要組件有哪些,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)具有一定的參考借鑒價值,需要的朋友可以參考
    2023-08-08
  • 如何使用Python實(shí)現(xiàn)PPT批量轉(zhuǎn)圖片

    如何使用Python實(shí)現(xiàn)PPT批量轉(zhuǎn)圖片

    這篇文章主要為大家詳細(xì)介紹了如何使用Python開發(fā)一個帶有圖形界面的PPT批量轉(zhuǎn)圖片工具,文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下
    2025-02-02
  • Python列表刪除重復(fù)元素與圖像相似度判斷及刪除實(shí)例代碼

    Python列表刪除重復(fù)元素與圖像相似度判斷及刪除實(shí)例代碼

    這篇文章主要給大家介紹了關(guān)于Python列表刪除重復(fù)元素與圖像相似度判斷及刪除的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05
  • python關(guān)于多值參數(shù)的實(shí)例詳解

    python關(guān)于多值參數(shù)的實(shí)例詳解

    在本篇內(nèi)容里小編給大家整理了一篇關(guān)于python關(guān)于多值參數(shù)的實(shí)例詳解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2021-07-07
  • 判斷網(wǎng)頁編碼的方法python版

    判斷網(wǎng)頁編碼的方法python版

    這篇文章主要為大家詳細(xì)介紹了python代碼判斷網(wǎng)頁編碼的方法,感興趣的小伙伴們可以參考一下
    2016-08-08
  • pymysql 開啟調(diào)試模式的實(shí)現(xiàn)

    pymysql 開啟調(diào)試模式的實(shí)現(xiàn)

    這篇文章主要介紹了pymysql 開啟調(diào)試模式的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • python re正則匹配網(wǎng)頁中圖片url地址的方法

    python re正則匹配網(wǎng)頁中圖片url地址的方法

    今天小編就為大家分享一篇python re正則匹配網(wǎng)頁中圖片url地址的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛

    基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛

    這篇文章主要介紹了基于python分析你的上網(wǎng)行為 看看你平時上網(wǎng)都在干嘛,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python中Pyenv virtualenv插件的使用

    Python中Pyenv virtualenv插件的使用

    pyenv是管理python版本的工具。安裝pyenv后,可以管理各種python版本,并且各個版本的環(huán)境完全獨(dú)立,互不干擾。今天通過本文給大家分享Python中Pyenv virtualenv插件的使用,感興趣的朋友一起看看吧
    2021-06-06

最新評論

忻州市| 民和| 栾城县| 梅河口市| 建宁县| 和硕县| 陈巴尔虎旗| 盱眙县| 方山县| 仁布县| 寻甸| 阿荣旗| 昌平区| 桐梓县| 富民县| 福州市| 黄龙县| 宝兴县| 颍上县| 博罗县| 东乡县| 互助| 永善县| 黄大仙区| 巩留县| 蓬安县| 福泉市| 苗栗县| 靖江市| 东阳市| 安乡县| 鹤峰县| 云安县| 教育| 久治县| 阳新县| 北海市| 开远市| 沂水县| 乐亭县| 韶山市|