本文整理汇总了Python中pydub.AudioSegment.from_file方法的典型用法代码示例。如果您正苦于以下问题:Python AudioSegment.from_file方法的具体用法?Python AudioSegment.from_file怎么用?Python AudioSegment.from_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydub.AudioSegment
的用法示例。
在下文中一共展示了AudioSegment.from_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: responseToAnAudioCachonism
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def responseToAnAudioCachonism(self, bot, update):
message= update["message"]
user= message.from_user["username"]
if user=="":
user= message.from_user["first_name"]
responseText= "Hey %s. Soy TeofiBot. Mira lo que hago con tu nota de voz..." % user
if user not in ["TeoGol29"]:
downAudio= bot.getFile(message.voice.file_id)
urllib.urlretrieve (downAudio.file_path, downAudio.file_id)
sound1 = AudioSegment.from_file(downAudio.file_id)
source_path= self.get_resource_path("sounds", "mi_creador.mp3")
sound2 = AudioSegment.from_file(source_path)
sound1 = sound1 + 1
sound2 = sound2 - 8
combined = sound1.overlay(sound2)
audio_mix_filename="mix_"+downAudio.file_id
combined.export(audio_mix_filename , format='mp3')
bot.sendMessage(chat_id=update.message.chat_id, text=responseText)
bot.sendAudio(chat_id=update.message.chat_id, audio=open(audio_mix_filename, 'rb'), caption='TeofiBot saboteandote con sabor')
os.remove(downAudio.file_id)
os.remove(audio_mix_filename)
示例2: match_length
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def match_length(input_path, output_path, match_path, force=False):
"""
Speeds up or slows down a wav file so that the length matches the length of another wav file.
:param input_path: the input wav path
:param output_path: the output wav path
:param match_path: the path of the wav to match the length of
:param force: call recursively if the input_path and match_path lengths vary greatly (not in betwee 0.5 and 2.0)
:returns: -1 if a file does not exist or ffmpeg fails
"""
if check_file_paths([input_path, match_path]) == -1:
return -1
input_segment = AudioSegment.from_file(input_path)
input_length = input_segment.duration_seconds
match_segment = AudioSegment.from_file(match_path)
match_seg_length = match_segment.duration_seconds
length_coefficient = input_length / match_seg_length
if length_coefficient < 2.0 and length_coefficient > 0.5:
change_length(input_path, output_path, length_coefficient)
return 0
if force:
if length_coefficient > 2.0:
change_length(input_path, input_path, 2.0)
match_length(input_path, output_path, match_path, force=True)
else:
change_length(input_path, input_path, 0.5)
match_length(input_path, output_path, match_path, force=True)
else:
print 'wrong size'
return -1
示例3: render
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def render(mix_id, *args):
minimum = sys.maxint
for arg in args:
if arg[0] < minimum:
minimum = arg[0]
for arg in args:
arg[0] -= minimum
prio_queue = Queue.PriorityQueue()
for arg in args:
prio_queue.put(arg)
base = prio_queue.get(0)
base_track = AudioSegment.from_file(base[1], "m4a")
gain = base[2]
base_track = base_track.apply_gain(gain)
while not prio_queue.empty():
overlay = prio_queue.get(0)
overlay_track = AudioSegment.from_file(overlay[1], "m4a")
gain = overlay[2]
if gain != 0:
overlay_track = overlay_track.apply_gain(gain)
base_track = base_track.overlay(overlay_track, position=overlay[0])
base_track.export('mix.wav', format='wav')
command = 'ffmpeg -b 66k -y -f wav -i ./mix.wav ./mix.aac'
subprocess.call(command, shell=True)
os.remove('mix.wav')
# concaac(mix_id, [0, "test1.m4a", 0], [5000, "test2.m4a", -10], [10000, "test3.m4a", 5])
示例4: outputTrack
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def outputTrack(playList):
au_file(name='master.au', freq=0, dur=playList[len(playList)-1][0][1], vol=0.2)
masterSong = AudioSegment.from_file("master.au", "au")
for item in playList:
#obten la longitudDelSegmento
longitudDelSegmento = int(item[0][1]) - int(item[0][0])
#obten Si se loopea
loops = item[2]
#crea los sonidos de esta seccion
sonidoNum = 1 #integra un contador para los sonidos
#crea un sonido temporal que contendra toda esta seccion
au_file(name="instrumento.au", freq=0, dur=longitudDelSegmento, vol=1)
for itemSonido in item[1]:
nombre = 'sound' + str(sonidoNum) +".au"
#print(nombre,itemSonido[2],itemSonido[1], float(itemSonido[0]))
au_file(name=nombre, freq=int(itemSonido[2]), dur=int(itemSonido[1]), vol=float(itemSonido[0]))
sonidoNum += 1
instrumento = AudioSegment.from_file("instrumento.au", "au")
for i in range(1, sonidoNum):
nombre = 'sound' + str(i) +".au"
#abreElArchivo
temp = AudioSegment.from_file(nombre, "au")
#insertaloEnElinstrumento
instrumento = instrumento.overlay(temp, position=0, loop=loops)
#concatenaElInstrumento
instrumento = instrumento[:longitudDelSegmento]
#sobrelapa los sonidos en master
masterSong = masterSong.overlay(instrumento, position=int(item[0][0]))
#final = masterSong*2
masterSong.export("testingSong.emepetres", format="mp3")
示例5: test_audio_segment_from_path_like_bytes
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def test_audio_segment_from_path_like_bytes(self):
seg1 = AudioSegment.from_file(self.mp3_path_str)
seg2 = AudioSegment.from_file(self.mp3_path_like_bytes)
self.assertEqual(len(seg1), len(seg2))
self.assertEqual(seg1._data, seg2._data)
self.assertTrue(len(seg1) > 0)
示例6: GetVoice
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def GetVoice(word): # https://tts.voicetech.yandex.net/generate?text=text&key=3f874a4e-723d-48cd-a791-7401169035a0&format=mp3&speaker=zahar&emotion=good
req =('https://tts.voicetech.yandex.net/generate?ie=UTF-8&text='+word+'&key='+API_KEY_VOICE+'&format=mp3&speaker=ermil&emotion=neutral')
response = requests.get(req, stream=True)
with open("yasound.mp3", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
AudioSegment.from_file('yasound.mp3').export("yasound.ogg", format="ogg")
示例7: export_wav
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def export_wav(self, filename):
n = self.song.num_tracks
self.song.export_song("temp/song.abc")
sounds = ["--syn_a", "--syn_b", "--syn_s", "--syn_e"]
for i in range(n):
os.system(
"python read_abc.py temp/song.abc "
+ str(i + 1)
+ " temp/out_"
+ str(i + 1)
+ ".wav "
+ random.choice(sounds)
)
os.remove("temp/song.abc")
combined = AudioSegment.from_file("temp/out_1.wav")
if n >= 2:
for i in range(1, n):
sound = AudioSegment.from_file("temp/out_" + str(i + 1) + ".wav")
combined = combined.overlay(sound)
combined.export(filename, format="wav")
for i in range(n):
os.remove("temp/out_" + str(i + 1) + ".wav")
示例8: convertFile
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def convertFile(self, url, local, verbose=True):
try:
if verbose:
print ' (downloading ' + local + ')'
format = url[-3:]
localMp3 = local[:-4] + '.mp3'
if settings.localTemp[-1] != '/':
settings.localTemp += '/'
if settings.localPublish[-1] != '/':
settings.localPublish += '/'
localTempFile = settings.localTemp + local
localMp3File = settings.localPublish + localMp3
localMp3URL = settings.localPublishRelative + localMp3
if format != 'mp3':
if utils.downloadFile(url, localTempFile):
if settings.FFMpegLocation != '':
AudioSegment.converter = settings.FFMpegLocation
AudioSegment.from_file(localTempFile).export(localMp3File, format='mp3', bitrate='96k')
# THEN add an updated media URL and media type
# THEN add a cleanup routine to delete copies that are not in top x00
# THEN add a routine to do this update for already-stored media
os.remove(localTempFile)
except:
err = str(sys.exc_info()[0]) + ' -> ' + str(sys.exc_info()[1])
log.log('ERROR', err)
localMp3URL = ''
return localMp3URL
示例9: get_data
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def get_data(path):
"""
Gets the data associated with an audio file, converting to wav when necessary.
:param path: path to audio file
:return: sample rate, audio data
"""
if path.endswith(".wav"):
bee_rate, bee_data = read(path)
else:
temp = tempfile.NamedTemporaryFile(suffix=".wav")
temp.close()
if path.endswith(".flac"):
sound = AudioSegment.from_file(path, "flac")
sound.export(temp.name, format="wav")
elif path.endswith(".mp3"):
sound = AudioSegment.from_file(path, "mp3")
sound.export(temp.name, format="wav")
bee_rate, bee_data = read(temp.name)
os.remove(temp.name)
data_type = np.iinfo(bee_data.dtype)
dmin = data_type.min
dmax = data_type.max
bee_data = bee_data.astype(np.float64)
bee_data = 2.0 * ((bee_data - dmin) / (dmax - dmin)) - 1.0
bee_data = bee_data.astype(np.float32)
return bee_rate, bee_data
示例10: audiodata_getter
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def audiodata_getter(path, date, filedate, filename, index):
#Check to see if it's a wav file. If not, convert in a temp file.
splitname = os.path.splitext(filename)[0]
if os.path.splitext(filename)[1] != ".wav":
temp = tempfile.NamedTemporaryFile(suffix=".wav")
if os.path.splitext(filename)[1] == ".mp3":
if "mp3" in path and date is None:
sound = AudioSegment.from_file(path + filedate[index] + "/" + filename, "mp3")
else:
sound = AudioSegment.from_file(path + filename, "mp3")
sound.export(temp.name, format = "wav")
if os.path.splitext(filename)[1] == ".flac":
if "mp3" in path and date is None:
sound = AudioSegment.from_file(path + filedate[index] + "/" + filename, "flac")
else:
sound = AudioSegment.from_file(path + filename, "flac")
sound.export(temp.name, format = "flac")
try:
wav = wave.open(temp, 'r')
return wav
except:
print(filename + " corrupted or not audio file.")
else:
try:
#Open the .wav file and get the vital information
wav = wave.open(path + "/audio/" + filename, 'r')
return wav
except:
print(filename + " corrupted or not audio file.")
示例11: mixer
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def mixer(first_path, second_path, mix_path, tag=None, f_format='wav'):
'''
ffmpeg or avconv are required for MP3 format mixing.
WAV format must be 8, 16, or 32 bit (24 bit is not supported by pydub)
'''
with open(first_path, 'rb') as f:
first = AudioSegment.from_file(f, format=f_format)
with open(second_path, 'rb') as f:
second = AudioSegment.from_file(f, format=f_format)
if len(first) > len(second):
mix = first.overlay(second)
else:
mix = second.overlay(first)
mix.export(mix_path, format=f_format)
metadata = {
'tag': tag,
'first_file': {
'path': first_path,
'length': first.duration_seconds
},
'second_file': {
'path': second_path,
'length': second.duration_seconds
},
'mix': {
'path': mix_path,
'length': mix.duration_seconds
}
}
return metadata
示例12: test_exporting_to_ogg_uses_default_codec_when_codec_param_is_none
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def test_exporting_to_ogg_uses_default_codec_when_codec_param_is_none(self):
with NamedTemporaryFile('w+b', suffix='.ogg') as tmp_ogg_file:
AudioSegment.from_file(self.mp4_file_path).export(tmp_ogg_file, format="ogg")
info = mediainfo(filepath=tmp_ogg_file.name)
self.assertEqual(info["codec_name"], "vorbis")
self.assertEqual(info["format_name"], "ogg")
示例13: test_non_existant_path_like_str
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def test_non_existant_path_like_str(self):
path = self.MyPathLike('this/path/should/not/exist/do/not/make/this/exist')
with self.assertRaises(FileNotFoundError):
_ = AudioSegment.from_file(path)
path = self.MyPathLike('')
with self.assertRaises(FileNotFoundError):
_ = AudioSegment.from_file(path)
示例14: test_non_existant_path_like_bytes
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def test_non_existant_path_like_bytes(self):
path = self.MyPathLike(bytes('this/path/should/not/exist/do/not/make/this/exist', sys.getdefaultencoding()))
with self.assertRaises(FileNotFoundError):
_ = AudioSegment.from_file(path)
path = self.MyPathLike(bytes('', sys.getdefaultencoding()))
with self.assertRaises(FileNotFoundError):
_ = AudioSegment.from_file(path)
示例15: store_as_wav
# 需要导入模块: from pydub import AudioSegment [as 别名]
# 或者: from pydub.AudioSegment import from_file [as 别名]
def store_as_wav(audioTrack):
if audioTrack.endswith('.wav'):
song = AudioSegment.from_file(audioTrack, "wav")
elif audioTrack.endswith('.m4a'):
song = AudioSegment.from_file(audioTrack, "m4a")
else:
song = AudioSegment.from_file(audioTrack, "mp3")
wave_song = song.export('temp.wav', format='wav')