Python语音识别转换mp3文件时出错

问题描述 投票:0回答:3

我第一次尝试音频转文本。

import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("/path/to/.mp3") as source:
     audio = r.record(source)

当我执行上面的代码时,出现以下错误,

<ipython-input-10-72e982ecb706> in <module>()
----> 1 with sr.AudioFile("/home/yogaraj/Documents/Python workouts/Python audio to text/show_me_the_meaning.mp3") as source:
      2     audio = sr.record(source)
      3 

/usr/lib/python2.7/site-packages/speech_recognition/__init__.pyc in __enter__(self)
    197                 aiff_file = io.BytesIO(aiff_data)
    198                 try:
--> 199                     self.audio_reader = aifc.open(aiff_file, "rb")
    200                 except aifc.Error:
    201                     assert False, "Audio file could not be read as WAV, AIFF, or FLAC; check if file is corrupted"

/usr/lib64/python2.7/aifc.pyc in open(f, mode)
    950             mode = 'rb'
    951     if mode in ('r', 'rb'):
--> 952         return Aifc_read(f)
    953     elif mode in ('w', 'wb'):
    954         return Aifc_write(f)

/usr/lib64/python2.7/aifc.pyc in __init__(self, f)
    345             f = __builtin__.open(f, 'rb')
    346         # else, assume it is an open file object already
--> 347         self.initfp(f)
    348 
    349     #

/usr/lib64/python2.7/aifc.pyc in initfp(self, file)
    296         self._soundpos = 0
    297         self._file = file
--> 298         chunk = Chunk(file)
    299         if chunk.getname() != 'FORM':
    300             raise Error, 'file does not start with FORM id'

/usr/lib64/python2.7/chunk.py in __init__(self, file, align, bigendian, inclheader)
     61         self.chunkname = file.read(4)
     62         if len(self.chunkname) < 4:
---> 63             raise EOFError
     64         try:
     65             self.chunksize = struct.unpack(strflag+'L', file.read(4))[0]

我不知道我出了什么问题。有人能告诉我上面的代码有什么问题吗?

python speech-recognition speech-to-text
3个回答
10
投票

Speech recognition
支持WAV文件格式。 这是使用
speech_recognition
的示例 WAV 到文本程序:

示例代码(Python 3)

import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("woman1_wb.wav") as source:
    audio = r.record(source)

try:
    s = r.recognize_google(audio)
    print("Text: "+s)
except Exception as e:
    print("Exception: "+str(e))

输出:

Text: to administer medicine to animals is frequency of very difficult matter and yet sometimes it's necessary to do so

使用的WAV文件网址:http://www-mobile.ecs.soton.ac.uk/hth97r/links/Database/woman1_wb.wav


6
投票

这就是错误所在:

语音识别仅支持WAV文件格式。

但这是关于如何获取 MP3 到文本的更完整答案:

这是一个处理函数,使用

speech_recognition
pydub
将 MP3 转换为 WAV,然后使用 Google 的语音 API 将 MP3 转换为 TEXT。它将 MP3 文件分成 60 秒的部分,以符合 Google 的限制,并允许您在一天内播放大约 50 分钟的音频。但50次API调用后它会阻止你。

from pydub import AudioSegment # uses FFMPEG
import speech_recognition as sr

def process(filepath, chunksize=60000):
    #0: load mp3
    sound = AudioSegment.from_mp3(filepath)

    #1: split file into 60s chunks
    def divide_chunks(sound, chunksize):
        # looping till length l
        for i in range(0, len(sound), chunksize):
            yield sound[i:i + chunksize]
    chunks = list(divide_chunks(sound, chunksize))
    print(f"{len(chunks)} chunks of {chunksize/1000}s each")

    r = sr.Recognizer()
    #2: per chunk, save to wav, then read and run through recognize_google()
    string_index = {}
    for index,chunk in enumerate(chunks):
        #TODO io.BytesIO()
        temp = 'temp.wav'
        chunk.export(temp, format='wav')
        with sr.AudioFile(temp) as source:
            audio = r.record(source)
        #s = r.recognize_google(audio, language="en-US") #, key=API_KEY) --- my key results in broken pipe
        s = r.recognize_google(audio, language="en-US")
        string_index[index] = s
        break
    return ' '.join([string_index[i] for i in range(len(string_index))])

audio_file_name = 'audio.mp3'
text = process(audio_file_name)
print(text)

我的测试 MP3 文件是来自 archive.org 的布道: https://ia801008.us.archive.org/24/items/UUCMService20190602IfWeBuildIt/UUCM%20Service%202019-06-02%20-%20If%20We%20Build%20It.mp3

这是返回的文本(每行是 60 秒的音频):

13 chunks of 60.0s each
please join me in a spirit of prayer Spirit of Life known in many ways by a million names gracious Spirit of Life unfolding never known in its fullness be with us hear our cries for deliverance dance with us in exultation hold us when we fall keep before us the reality that every day is a gift to be unwrapped a gift to help discover why we live why we are cast Here and Now
Austin teaches us that the days come and go like muffled veiled figures Sent From A Distant friendly party but they say nothing and if we do not use the gifts they bring us they will carry them away as silently as they came through buying source of all Bend us towards gratitude and compassion Modern Life demands much misery and woe get created all around us but there is more much more show us that much more belongs to us to light Dawns on those who live love and sing the truth Joy John's on those who humbly toiled
do what is just so you who can shine pass on your light when it Dawns on you and let us all find the space to see Life as a gift to see our days as blessings and let us return life's gift and promise with grateful hearts and acts of kindness in the name of all the each of us teams holiest within our hearts we pray Amon
my character at least when I was younger I'm sure I don't really do this anymore the most challenging aspect of my character is that I want wisdom yesterday I don't want to have to learn something now I should have known it already right I used to drive my poor parents crazy as they tried to help me with my homework my father with my math my mother with my spelling if I didn't know the answer as soon as the problem was in front of me I would get angry frustrated with myself how come I didn't already know that I'm supposed to be wise only child I wonder if that has anything to do around the room has been throughout my life
but I still see it manifest in one particular aspects of my being I want us all to know how to love one another perfectly with wisdom already we should have learned that yesterday I want the Beloved Community right now and it frustrates me to no end that it isn't here what was that song that we saying after the prayer response how could anyone ever tell you you were anything less than beautiful how do we do that how do we tell ourselves that and others that we are not all the time how do we do that how come we haven't figured that out yesterday there's been a great Salve and corrective
to this challenge of my personality that I found in Community First the bomb the South I find the in community in this started when I was a youth in my youth group when we were ten people sitting on a floor together on pillows telling one another about what we've been through that week and how much pain we were carrying and how much we needed one another I found in that youth group with just 10 of us are sitting on the floor that we could be the Beloved Community for one another if only just for one hour a week sometimes just for 5 minutes sometimes just for a moment that was the Sal that was the bomb I realize that maybe we can't do it all the time but we can do it in moments and in spaces and that only happen for me in the space
community that community that we created with one another and the corrective to my need to have things everything done yesterday that also happens in community because Community is the slowest place on Earth We're going to have our annual meeting later let's see how slow that's going to be but the truth of the matter is that even in that slowness when you're working really hard to set up or cleanup connection Cafe when you're trying to figure out how to set up membership so that we actually do talk to everybody who comes through the doors right when you're doing that work of the Care team and that big list of all the different people that we need to reach out to and and we have to figure out how we reached out to all of them and who's done it
when you're waiting for the sermon to be over in all of these waiting times and all of these phases of process what I've learned in that slowness something amazing something remarkable is happening we are dedicating ourselves over and over again to still being together cuz it's not always easy because we're all broken and we're all whole because sometimes this is incredibly difficult and painful but when we're in those times what we're doing is we're saying it's worth it something about this matters to me and to all of us and Becca's got a great story to illustrate the this comes from
used to have a radio show in Boston maybe you heard him at some point Unitarian Universalist Minister from Boston 66 driving lessons and five road test she was 70 years old and had never driven a car but on July 25th 1975 she went to the Rockland County driving school and took her first lesson her husband had already had heart trouble and might someday be unable to drive if that happened she wanted to be the one to do the shopping and Shake him to the doctor she began the slow and painful process of learning to start stop turn into traffic back up after 5 difficult month she took the driving test
before ever she wrote in her diary and was not nervous she just a test a month later and slumped again I did everything wrong she told her diary demonic in August of 1976 she resumed the lessons with the Eaton driving school and took her third road test in October with half the world praying for me
she took a double driving lesson the next day and parallel park 6 times after three more lessons she took her Fifth and final test on January 21st 1977 and passed she had spent $860 on 66 plus 5 road test and at the age of 71 she had her license good three years later he did for several months she was the one who drove to the hospital Supermarket Pharmacy in church when we were children
someone rafter do another instructed by the spider's persistence Robert brute Robert Bruce left the Hut gathered his men and defeated the dance my mother and body of the story but it was not just persistence that moved her but love for the man who was her other self do you want to know what love is it's 66 driving lessons and five road tests and a very tough lady
who won't give up because her love is that great thank you all for bringing this to this beloved in moments community

免费真是太好了。不幸的是,如果我想转录几个小时的内容,谷歌云 API 版本就太贵了。


0
投票

语音识别支持WAV文件格式。这是使用语音识别的示例 MP3 到文本程序

import speech_recognition as sr
from pydub import AudioSegment

r = sr.Recognizer()
#convert mp3 to wav
sound = AudioSegment.from_mp3("recording.mp3")
sound.export("recording.wav", format="wav")
temp = 'recording.wav'
with sr.AudioFile(temp) as source:
        audio = r.record(source)
text = r.recognize_google(audio, language="en-US")
print(text)

你必须使用安装 pydub

$ sudo apt 更新

$ sudo apt install ffmpeg

© www.soinside.com 2019 - 2024. All rights reserved.