Convert .wav file to .ogg format in python

  python, python-3.x

I record sound from a microphone and record it in a folder with wav format and I need to convert it to ogg format in order to send it to the server.

`import pyaudio
import wave
from os import path
from pydub import AudioSegment
import tempfile
from urllib.request import urlopen

sample_format = pyaudio.paFloat32  # 16 bits per sample
channels = 1
fs = 44100  # Record at 44100 samples per second
seconds = 3
filename = "input.wav"
chunk = 1024#fs*5  # Record in chunks of 1024 samples


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

print('Recording')

stream = p.open(format=sample_format,
                channels=channels,
                rate=fs,
                frames_per_buffer=chunk,
                input=True)

frames = []  # Initialize array to store frames

# Store data in chunks for 3 seconds
for i in range(0, int(fs / chunk * seconds)):
    data = stream.read(chunk, exception_on_overflow=False)
    frames.append(data)

# Stop and close the stream 
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()

print('Finished recording')

# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()


dst = "output.ogg"

sound = AudioSegment.from_wav(filename)
sound.export(dst, format="ogg")`

But I always get errors, first I converted to mp3 format and then to ogg, but there was an error that it was impossible to write a byte object to str. And somewhere I dug up this method and, in theory, it should be working, but it gives an error

`Traceback (most recent call last):
  File "C:UsersOlegDesktoptesttest2.py", line 53, in <module>
    sound.export(dst, format="ogg")
  File "C:UsersOlegAppDataLocalProgramsPythonPython310libsite-packagespydubaudio_segment.py", line 963, in export
    p = subprocess.Popen(conversion_command, stdin=devnull, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  File "C:UsersOlegAppDataLocalProgramsPythonPython310libsubprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:UsersOlegAppDataLocalProgramsPythonPython310libsubprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2]The specified file cannot be found`

but all files are in one file. And when I converted to mp3 format everything worked.

Source: Python-3x Questions

LEAVE A COMMENT