本文整理匯總了Python中pydub.AudioSegment.from_mp3方法的典型用法代碼示例。如果您正苦於以下問題:Python AudioSegment.from_mp3方法的具體用法?Python AudioSegment.from_mp3怎麽用?Python AudioSegment.from_mp3使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pydub.AudioSegment
的用法示例。
在下文中一共展示了AudioSegment.from_mp3方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: load_audio
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def load_audio(filepath, sr=None, mono=True, dtype='float32'):
if '.mp3' in filepath:
from pydub import AudioSegment
import tempfile
import os
mp3 = AudioSegment.from_mp3(filepath)
_, path = tempfile.mkstemp()
mp3.export(path, format="wav")
del mp3
x, fs = sf.read(path)
os.remove(path)
else:
x, fs = sf.read(filepath)
if mono and len(x.shape)>1:
x = np.mean(x, axis = 1)
if sr:
x = scipy.signal.resample_poly(x, sr, fs)
fs = sr
x = x.astype(dtype)
return x, fs
示例2: extract_words
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def extract_words(files):
''' Extracts individual words form files and exports them to individual files. '''
output_directory = 'extracted_words'
if not os.path.exists(output_directory):
os.makedirs(output_directory)
for f in files:
file_format = None
source_segment = None
if f.lower().endswith('.mp3'):
file_format = 'mp3'
source_segment = AudioSegment.from_mp3(f)
elif f.lower().endswith('.wav'):
file_format = 'wav'
source_segment = AudioSegment.from_wav(f)
if not file_format or source_segment:
print('Unsupported audio format for ' + f)
sentences = convert_timestamps(files)
for s in sentences:
for word in s['words']:
start = float(word[1]) * 1000
end = float(word[2]) * 1000
word = word[0]
total_time = end - start
audio = AudioSegment.silent(duration=total_time)
audio = audio.overlay(source_segment[start:end])
number = 0
output_path = None
while True:
output_filename = word
if number:
output_filename += "_" + str(number)
output_filename = output_filename + '.' + file_format
output_path = os.path.join(output_directory, output_filename)
if not os.path.exists(output_path):
# this file doesn't exist, so we can continue
break
# file already exists, increment name and try again
number += 1
print('Exporting to: ' + output_path)
audio.export(output_path, format=file_format)
示例3: convert_mp3_to_wav
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def convert_mp3_to_wav(mp3_path):
"""
將 mp3 文件轉成 wav
:param mp3_path: mp3 文件路徑
:returns: wav 文件路徑
"""
target = mp3_path.replace(".mp3", ".wav")
if not os.path.exists(mp3_path):
logging.critical("文件錯誤 {}".format(mp3_path))
return None
AudioSegment.from_mp3(mp3_path).export(target, format="wav")
return target
示例4: mp3_to_wav
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def mp3_to_wav(src_path, tar_path):
"""
Read mp3 file from source path, convert it to wav and write it to target path.
Necessary libraries: ffmpeg, libav.
:param src_path: source mp3 file path
:param tar_path: target wav file path
"""
basepath, filename = os.path.split(src_path)
os.chdir(basepath)
AudioSegment.from_mp3(src_path).export(tar_path, format='wav')
示例5: load_audio_file
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def load_audio_file(filename,resize=False):
sound = None
try:
if filename.endswith('.mp3') or filename.endswith('.MP3'):
sound = AudioSegment.from_mp3(filename)
elif filename.endswith('.wav') or filename.endswith('.WAV'):
sound = AudioSegment.from_wav(filename)
elif filename.endswith('.ogg'):
sound = AudioSegment.from_ogg(filename)
elif filename.endswith('.flac'):
sound = AudioSegment.from_file(filename, "flac")
elif filename.endswith('.3gp'):
sound = AudioSegment.from_file(filename, "3gp")
elif filename.endswith('.3g'):
sound = AudioSegment.from_file(filename, "3gp")
sound = sound.set_frame_rate(samplerate)
sound = sound.set_channels(1)
sound = sound.set_sample_width(2)
duration = sound.duration_seconds
except:
print("Couldn't load file")
return None,None
return sound,duration
示例6: text_to_speech
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def text_to_speech(self, speech):
speech = remove_ansi_escape_seq(speech)
tts = gTTS(speech, lang="en")
tts.save("voice.mp3")
audio = AudioSegment.from_mp3('voice.mp3')
playback.play(audio)
os.remove("voice.mp3")
示例7: convert
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def convert(song=song_path):
sound = AudioSegment.from_mp3(song)
# get the raw data
raw_data = sound._data
return raw_data
示例8: convert_to_music
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def convert_to_music(bytes):
song = AudioSegment.from_file(io.BytesIO(bytes), format="mp3")
output = io.StringIO()
song.export(output, format="mp3", bitrate="192k")
converted_sound = AudioSegment.from_mp3(cwd + "/music/copy.mp3")
print("Done")
示例9: use_cloud
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def use_cloud(self, sourcefile_path, token):
# sound = AudioSegment.from_mp3("big.mp3")
# sound.export("/output", format="wav")
fp = wave.open(sourcefile_path, 'rb')
nf = fp.getnframes()
f_len = nf * 2
audio_data = fp.readframes(nf)
cuid = "xxxxxxxxxx" # my xiaomi phone MAC
srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
http_header = [
'Content-Type: audio/pcm; rate=8000',
'Content-Length: %d' % f_len
]
c = pycurl.Curl()
c.setopt(pycurl.URL, str(srv_url)) # curl doesn't support unicode
# c.setopt(c.RETURNTRANSFER, 1)
c.setopt(c.HTTPHEADER, http_header) # must be list, not dict
c.setopt(c.POST, 1)
c.setopt(c.CONNECTTIMEOUT, 30)
c.setopt(c.TIMEOUT, 30)
c.setopt(c.WRITEFUNCTION, self.dump_res)
c.setopt(c.POSTFIELDS, audio_data)
c.setopt(c.POSTFIELDSIZE, f_len)
c.perform() # pycurl.perform() has no return val
示例10: getOutput
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def getOutput(sourcefile_path, targetfile_path):
song = AudioSegment.from_mp3(sourcefile_path).export(targetfile_path, format="wav")
voiceService = VoiceService()
voiceService.voicepro(targetfile_path)
while True:
if voiceService.isOk:
usage = json.loads(voiceService.buff)
result = usage['result']
return result
示例11: v2t
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def v2t(voice_data):
try:
wav_file_path = config.wxbot_cache_path + "/out.wav"
audio = AudioSegment.from_mp3(BytesIO(voice_data))
audio.export(wav_file_path, format="wav")
with open(wav_file_path,'rb') as f:
data = f.read()
if config.voice2txt_engine=="baidu":
return _covert2text_baidu(data)
else:
return _covert2text_xunfei(data)
except Exception as e :
logger.exception(e,"轉化語音識別失敗"+str(e))
return None
示例12: get_challenge_audio
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def get_challenge_audio(self, url):
# Download the challenge audio and store in memory
request = requests.get(url)
audio_file = io.BytesIO(request.content)
# Convert the audio to a compatible format in memory
converted_audio = io.BytesIO()
sound = AudioSegment.from_mp3(audio_file)
sound.export(converted_audio, format="wav")
converted_audio.seek(0)
return converted_audio
示例13: convert
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def convert(mp3):
sound = AudioSegment.from_mp3(mp3)
sound.export(mp3.replace(".mp3", ".wav"), format="wav")
return mp3.replace(".mp3", ".wav")
示例14: extract
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def extract(file):
"""
Extracts audio from a given file
First the audio is converted into wav format
"""
s = file.split('.')
file_format = s[len(s) - 1]
try:
song = AudioSegment.from_file(file, file_format)
#song = AudioSegment.from_mp3(file)
song = song[: 30 * 1000 ]
song.export(file[:-3] + "wav", format="wav")
file = file[:-3] + "wav"
except Exception as e:
print(e)
try:
(rate, data) = scipy.io.wavfile.read(file)
mfcc_feat = mfcc(data,rate)
#redusing mfcc dimension to 104
mm = np.transpose(mfcc_feat)
mf = np.mean(mm,axis=1)
cf = np.cov(mm)
ff=mf
#ff is a vector of size 104
for i in range(mm.shape[0]):
ff = np.append(ff,np.diag(cf,i))
if file_format != 'wav':
os.remove(file)
return ff.reshape(1, -1)
except Exception as e:
print(e)
示例15: mp3_to_ogg
# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_mp3 [as 別名]
def mp3_to_ogg(input_file_name): # caller should delete the file afterwards.
ogg_file = tempfile.NamedTemporaryFile(delete=False)
AudioSegment.from_mp3(input_file_name).export(ogg_file.name, format='ogg', parameters=["-acodec", "libopus"])
ogg_file.close()
return ogg_file.name