I want to make a speech recognition from a wav.
To do that, I have a wav that I split into multiple chunks, export them, and then use the SpeechRecognition library.
from pydub import AudioSegment
import speech_recognition as sr
r = sr.Recognizer()
for i in range(5):
audio = AudioSegment.from_wav("some_wav.wav")
audio_chunk=audio[int(i*1000):int(i*3000)]
audio_chunk.export('test.wav', format='wav')
detection = sr.AudioFile('test.wav')
with detection as source:
audio = r.record(source)
word = r.recognize_google(audio, language = 'ro-RO')
The problem is that this is not very optimal. I want to get rid of the export wav part. I want to transform the audio_chunk into bytes and then use it in the speechRecognition.AudioFile() with in-memory bytes.
Is there a way to convert the audio-segment type into bytes?
Is there any way to extract MXF (Material Exchange Format) file data using python?
All I want to do is get data like video duration, actual video stream and if possible the voice in mp3 or any audio format from an MXF file.
You can do those things using ffmpeg-python.
Example of how to extract video duration:
import ffmpeg
filename = 'sample_960x400_ocean_with_audio.mxf'
# Get duration
# Credit: https://github.com/kkroening/ffmpeg-python/issues/545#issuecomment-836792082
video_info = ffmpeg.probe(filename)
duration = float(video_info['format']['duration'])
print(f'Duration: {duration} seconds')
Example of how to convert the audio to MP3:
import ffmpeg
filename = 'sample_960x400_ocean_with_audio.mxf'
# Load file
in_file = ffmpeg.input(filename)
# Get audio track, convert to mp3
in_file.output('file.mp3').run()
Example of how to convert the audio and video to mp4:
import ffmpeg
filename = 'sample_960x400_ocean_with_audio.mxf'
# Load file
in_file = ffmpeg.input(filename)
# Get video, convert to mp4
in_file.output('file.mp4').run()
Note that to use ffmpeg-python, you must install both ffmpeg-python and ffmpeg. See the documentation for more.
After doing split in an audio file with Librosa, I want to know how to obtain the resultant fragments in mp3 filesSee audio image
Can you just open individual files like
fragment1 = open("x.mp3", "a")
fragment2 = open("y.mp3", "a")
and then write to each of those using what you have as variables?
I have generated a .wav audio file containing some speech with some other interference speech in the background.
This code worked for me for a test .wav file:
import speech_recognition as sr
r = sr.Recognizer()
with sr.WavFile(wav_path) as source:
audio = r.record(source)
text = r.recognize_google(audio)
If I use my .wav file, I get the following error:
ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format
The situation slightly improves if I save this .wav file with soundfile:
import soundfile as sf
wav, samplerate = sf.read(wav_path)
sf.write(saved_wav_path, original_wav, fs)
and then load the new saved_wav_path back into the first block of code, this time I get:
if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
The audio files were saved as
wavfile.write(wav_path, fs, data)
where wav_path = 'data.wav'. Any ideas?
SOLUTION:
Saving the audio data the following way generates the correct .wav files:
import wavio
wavio.write(wav_path, data, fs ,sampwidth=2)
From a brief look at the code in the speech_recognition package, it appears that it uses wave from the Python standard library to read WAV files. Python's wave library does not handle floating point WAV files, so you'll have to ensure that you use speech_recognition with files that were saved in an integer format.
SciPy's function scipy.io.wavfile.write will create an integer file if you pass it an array of integers. So if data is a floating point numpy array, you could try this:
from scipy.io import wavfile
# Convert `data` to 32 bit integers:
y = (np.iinfo(np.int32).max * (data/np.abs(data).max())).astype(np.int32)
wavfile.write(wav_path, fs, y)
Then try to read that file with speech_recognition.
Alternatively, you could use wavio (a small library that I created) to save your data to a WAV file. It also uses Python's wave library to create its output, so speech_recognition should be able to read the files that it creates.
I couldn't figure out what the sampwidth should be for wavio from its documentation; however, I added the following line sounddevice.default.dtype='int32', 'int32' which allowed sounddevice, scipy.io.wavfile.write / soundfile, and speech_recognizer to finally work together. The default dtype for sounddevice was float32 for both input and output. I tried changing only the output but it didnt work. Weirdly, audacity still thinks the output files are in float32. I am not suggesting this is a better solution, but it did work with both soundfile and scipy.
I also noticed another oddity. When sounddevice.default.dtype was left at the default [float32, float32] and I opened the resulting file in audacity. From audacity, I exported it and this exported wav would work with speechrecognizer. Audacity says its export is float32 and the same samplerate, so I don't fully understand. I am a noob but looked at both files in a hex editor and they look the same for the first 64 hex values then they differ... so it seems like the header is the same. Those two look very different than the file I made using int32 output, so seems like there's another factor at play...
Similar to Warren's answer, I was able to resolve this issue by rewriting the WAV file using pydub:
from pydub import AudioSegment
filename = "payload.wav" # File that already exists.
sound = AudioSegment.from_mp3(filename)
sound.export(filename, format="wav")
I have the following code to load a .wav file and play it:
import base64
import winsound
with open('file.wav','rb') as f:
data = base64.b64encode(f.read())
winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)
It plays the file no problem but now I would like to extract a 'chunk' let's say from 233 to 300 and play that portion only.
seg = data[233:300]
winsound.PlaySound(base64.b64decode(seg), winsound.SND_MEMORY)
I Get: TypeError: 'sound' must be str or None, not 'bytes'
PlaySound() is expecting a fully-formed WAV file, not a segment of PCM audio data. From the docs for PlaySound(), the underlying function called by Python's winsound:
The SND_MEMORY flag indicates that the lpszSoundName parameter is a pointer to an in-memory image of the WAVE file.
(emphasis added)
Rather than playing around with the internals of WAV files (though that isn't too hard, if you're interested), I'd suggest a more flexible audio library like pygame's. There, you could use the music module and it's set_pos function or use the Sound class to access the raw audio data and cut it like you proposed in your question.