简体   繁体   中英

How to save with .mp3 instead of .wav?

I'm trying to make a voice recorder, in this portion of code the file is saved with the .wav format but i prefere the .mp3 format, how to save the file with the .mp3 extension? I think that SoundFile can't use mp3 because if i write .mp3 instead of .wav the program gives me an error, thanks

with sf.SoundFile("output.wav", mode='w', samplerate=44100,channels=2) as file:
   #Create an input stream to record audio without a preset time
           with sd.InputStream(samplerate=44100, channels=2, callback=callback):
               while recording == True:
                   #Set the variable to True to allow playing the audio later
                   file_exists =True
                   #write into file
                   file.write(q.get())

Soundfile, or, more precisely, libsndfile , does not support mp3. Consider using a different library (eg pydub ). Here's an example where I am writing a sine wave to mp3:

import numpy as np
from pydub import AudioSegment

sample_rate = 48000
frequency = 440 # Hz
length = 3 # in seconds

t = np.linspace(0, length, sample_rate * length) 
y = np.sin(frequency * 2 * np.pi * t).astype("float32")  #  Has frequency of 440Hz

audio_segment = AudioSegment(
    y.astype("float32").tobytes(), 
    frame_rate=sample_rate,
    sample_width=y.dtype.itemsize, 
    channels=1
)

audio_segment.export("test.mp3", format="mp3", bitrate="128k")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM