Raise error file does not start with riff id

When running the first 14 lines of audio_transcribe.py, I receive the error below. What do I need to do to fix this? /usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/bin/p...

When running the first 14 lines of audio_transcribe.py, I receive the error below. What do I need to do to fix this?

/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/adamg/te/Polli/ASR/SpeechRecognitionTest0.py
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/speech_recognition/__init__.py", line 174, in __enter__
    self.audio_reader = wave.open(self.filename_or_fileobject, "rb")
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wave.py", line 497, in open
    return Wave_read(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wave.py", line 163, in __init__
    self.initfp(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wave.py", line 130, in initfp
    raise Error('file does not start with RIFF id')
wave.Error: file does not start with RIFF id

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/speech_recognition/__init__.py", line 179, in __enter__
    self.audio_reader = aifc.open(self.filename_or_fileobject, "rb")
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 887, in open
    return Aifc_read(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 340, in __init__
    self.initfp(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 305, in initfp
    raise Error('file does not start with FORM id')
aifc.Error: file does not start with FORM id

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/adamg/te/Polli/ASR/SpeechRecognitionTest0.py", line 13, in <module>
    with sr.AudioFile(AUDIO_FILE) as source:
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/speech_recognition/__init__.py", line 199, in __enter__
    self.audio_reader = aifc.open(aiff_file, "rb")
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 887, in open
    return Aifc_read(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 340, in __init__
    self.initfp(f)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/aifc.py", line 303, in initfp
    chunk = Chunk(file)
  File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/chunk.py", line 63, in __init__
    raise EOFError
EOFError

Process finished with exit code 1

wave.Error: file does not start with RIFF id and error.
In views.py

from mfcc import *
import numpy as np
import os
if __name__ == "__main__":
        train_label = np.array ([])
        test_label = np.array ([])
        nfft = 2048
        nceps = 12
        train_data = np.empty ((0, 12), float)
        test_data = np.empty ((0, 12), float)
        directory = os.listdir ('/ sound_app/sounds')
        for file_name in directory:
            feature = get_feature (file_name, nfft, nceps)
            if len (train_data) == 0:
                train_data = feature
            else:
                train_data = np.vstack ((train_data, feature))
                train_label = np.append (train_label)

            test_label = np.append (test_label, file_name)

And write to mfcc.py

import wave
import numpy as np
import scipy.signal
import scipy.fftpack
import scipy.fftpack.realtransforms
from pylab import *
def get_feature (wavfile, nfft, nceps):
    wav, fs = wavread (wavfile)
    t = np.arange (0.0, len (wav)/fs, 1/fs)
    center = len (wav)/2
    cuttime = 0.8
    global wavdata
    wavdata = wav [int (center-cuttime/2 * fs): int (center + cuttime/2 * fs)]
    global time
    time = t [int (center-cuttime/2 * fs): int (center + cuttime/2 * fs)]
    ceps = mfcc (wavdata, nfft, fs, nceps)
    return ceps.tolist ()

I wrote.
/ sound_app/sounds contains a lot of wav files, and when you type a command to check if these wav files are really wav files

RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 44100 Hz

I came back and confirmed that it was a wav file. Why do I get this error? How do I fix the error?

for Traceback

Traceback (most recent call last):
  File "sound.py", line 24, in&lt;module&gt;
    feature = get_feature (file_name, nfft, nceps)
  File "/Users/xxx/sound_recognition/mfcc.py", line 76, in get_feature
    wav, fs = wavread (wavfile)
  File "/Users/xxx/sound_recognition/mfcc.py", line 13, in wavread
    wf = wave.open (filename, "r")
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wave.py", line 511, in open
    return Wave_read (f)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wave.py", line 164, in __init__
    self.initfp (f)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wave.py", line 131, in initfp
    raise Error, 'file does not start with RIFF id'
wave.Error: file does not start with RIFF id

I came out.

Я пытаюсь преобразовать mp3-файл в текст, но мой код возвращает ошибку, описанную ниже. Любая помощь приветствуется!

Это образец mp3-файла. И вот что я пробовал:

import speech_recognition as sr
print(sr.__version__)
r = sr.Recognizer()

file_audio = sr.AudioFile(r"C:UsersAndrewPodcast.mp3")

with file_audio as source:
    audio_text = r.record(source)

print(type(audio_text))
print(r.recognize_google(audio_text))

Я получаю полную ошибку. По-видимому:

Error: file does not start with RIFF id

Спасибо за помощь!

2 ответа

Лучший ответ

Вам нужно сначала преобразовать mp3 в wav, а затем вы можете его расшифровать, ниже — измененная версия вашего кода.

import speech_recognition as sr
from pydub import AudioSegment

# convert mp3 file to wav  
src=(r"C:UsersAndrewPodcast.mp3")
sound = AudioSegment.from_mp3(src)
sound.export("C:UsersAndrewpodcast.wav", format="wav")

file_audio = sr.AudioFile(r"C:UsersAndrewPodcast.wav")

# use the audio file as the audio source                                        
r = sr.Recognizer()
with file_audio as source:
audio_text = r.record(source)

print(type(audio_text))
print(r.recognize_google(audio_text))

В приведенном выше модифицированном коде сначала конвертируется mp3-файл в wav, а затем выполняется расшифровка.


1

Meghshyam Sonar
2 Янв 2021 в 02:10

Единственное, что вы можете сделать, — это преобразовать ваш mp3 в wav. При тестировании с mp3 файлом у меня такая же ошибка, как и у вас. Но после преобразования ваш код работает нормально. Можно было бы также написать свой код, чтобы вы могли использовать mp3, но на этом мои знания заканчиваются.

Может быть, кто-то другой знает больше, чем я мог бы опубликовать. Но если вы просто хотите протестировать, вы можете использовать что-то вроде смелости, чтобы преобразовать его.

Также у вас могут возникнуть проблемы, если вы перейдете с большими файлами, прочтите что-нибудь об этом в Интернете. Но тебе ничто не мешает.

Вот сайт для этого:

https://www.geeksforgeeks.org/python-speech-recognition-on-large-audio-files/


1

Andreas B
2 Янв 2021 в 01:51

Всем доброго времени суток. Помогите, пожалуйста, в одном вопросе.

Пытаюсь на питоне реализовать передачу аудиоданных в потоке через сокет.
Как сделать, чтобы аудиофайл в сокет отправлялся порциями(по байтам)? Между порциями аудио в сокет должен отправляться разделитель «—audio».

Использую библиотеку PyAudio

Вот код целиком. При отладке сокет открывается, api запрос отправляется и по факту стрим должен начаться, но вылетает ошибка.

#######Подключаемые модули

import requests
import socket
import pyaudio
import wave


##########################

#######Открываем сокет для стрима
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('192.168.13.122', 80))

#######Передаем API запросы по HTTP POST
url = 'http://192.168.13.122/cgi-bin/transmitaudio_cgi?user=admin&pwd=admin HTTP'
headers = {'Content-Type': 'audio/basic', 'Content-Length': '99999999', 'Connection': 'Keep-Alive', 'Cache-Control': 'no-cache'}
r = requests.post(url, headers=headers)
print(requests.__file__)
print(dir(requests))

#######Транслируем звук

filename = 'voice.wav'

# Set chunk size of 1024 samples per data frame
chunk = 1024  

# Open the sound file 
wf = wave.open(filename, 'rb')

# Create an interface to PortAudio
p = pyaudio.PyAudio()

# Open a .Stream object to write the WAV file to
# 'output = True' indicates that the sound will be played rather than recorded
stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

# Read data in chunks
data = wf.readframes(chunk)

# Play the sound by writing the audio data to the stream
while data != '':
    stream.write(data)
    data = wf.readframes(chunk)

# Close and terminate the stream
stream.close()
p.terminate()

sock.close()

Ошибка

Traceback (most recent call last):
  File "C:UsersRomanDesktopПО HTTP Audiocgiaudio.py", line 30, in <module>
    wf = wave.open(filename, 'rb')
  File "C:UsersRomanAppDataLocalProgramsPythonPython37libwave.py", line 510, in open
    return Wave_read(f)
  File "C:UsersRomanAppDataLocalProgramsPythonPython37libwave.py", line 164, in __init__
    self.initfp(f)
  File "C:UsersRomanAppDataLocalProgramsPythonPython37libwave.py", line 131, in initfp
    raise Error('file does not start with RIFF id')
wave.Error: file does not start with RIFF id.

Понравилась статья? Поделить с друзьями:
  • Raise application error sqlerrm
  • Raise application error oracle пример
  • Raise application error oracle описание
  • Raise application error 20001
  • Raise activerecord connectionnotestablished error message