gTTS error: saving as wav but saved as MPEG

gTTS error: saving as wav but saved as MPEG

正在尝试使用 gTTS 模块将文本转换为语音并另存为 wav 文件。

我的代码:

import gTTS
text = "This is my text in the saving folder"
tts = gTTS(text)
tts.save('sample.wav')

文件已保存,但当我查看我的文件信息时:

$ mediainfo sample.wav
General
Complete name                            : sample.wav
Format                                   : MPEG Audio
File size                                : 15.8 KiB
Duration                                 : 4 s 32 ms
Overall bit rate mode                    : Constant
Overall bit rate                         : 32.0 kb/s
FileExtension_Invalid                    : m1a mpa1 mp1 m2a mpa2 mp2 mp3

Audio
Format                                   : MPEG Audio
Format version                           : Version 2
Format profile                           : Layer 3
Duration                                 : 4 s 32 ms
Bit rate mode                            : Constant
Bit rate                                 : 32.0 kb/s
Channel(s)                               : 1 channel
Sampling rate                            : 24.0 kHz
Compression mode                         : Lossy
Stream size                              : 15.8 KiB (100%)

为什么我得到不同的保存格式?

您可能无法保存它。 gTTS 提供了将音频剪辑保存为 mp3 的选项。即使您将名称命名为 .wav,它也不会识别并使用默认选项进行保存。以防万一,如果您需要单独使用 wav 文件,请使用 pydub 模块更改文件格式。

from pydub import AudioSegment
sound = AudioSegment.from_mp3("myfile.mp3")
sound.export("myfile.wav", format="wav")

您的代码中的错误在第一行

而不是使用import gTTS你应该使用:

from gtts import gTTS

通过这个简单的修改,您的文本转语音代码 运行 没问题,音频按预期以 .wav 格式保存。解决代码如下:

from gtts import gTTS 

# The text that you want to convert to audio 
mytext = "This is my text in the saving folder"

# Language in which you want to convert 
language = 'en'

# Passing the text and language to the engine
tts = gTTS(text=mytext, lang=language, slow=False) 

# Saving the converted audio in a wav file named sample
tts.save('sample.wav')