當前位置: 首頁>>代碼示例>>Python>>正文


Python AudioSegment.from_mp3方法代碼示例

本文整理匯總了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 
開發者ID:bill317996,項目名稱:Melody-extraction-with-melodic-segnet,代碼行數:25,代碼來源:cfp.py

示例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) 
開發者ID:antiboredom,項目名稱:audiogrep,代碼行數:43,代碼來源:audiogrep.py

示例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 
開發者ID:wzpan,項目名稱:wukong-itchat,代碼行數:15,代碼來源:bot.py

示例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') 
開發者ID:andabi,項目名稱:parallel-wavenet-vocoder,代碼行數:13,代碼來源:audio.py

示例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 
開發者ID:nyumaya,項目名稱:nyumaya_audio_recognition,代碼行數:29,代碼來源:test_accuracy.py

示例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") 
開發者ID:sukeesh,項目名稱:Jarvis,代碼行數:9,代碼來源:voice.py

示例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 
開發者ID:Ezi0aaudit0re,項目名稱:P2P-music-sharing,代碼行數:9,代碼來源:music.py

示例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") 
開發者ID:Ezi0aaudit0re,項目名稱:P2P-music-sharing,代碼行數:8,代碼來源:music.py

示例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 
開發者ID:agenthun,項目名稱:WeixinBot,代碼行數:28,代碼來源:baidu_voice.py

示例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 
開發者ID:agenthun,項目名稱:WeixinBot,代碼行數:11,代碼來源:baidu_voice.py

示例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 
開發者ID:newsettle,項目名稱:ns4_chatbot,代碼行數:16,代碼來源:voice2txt.py

示例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 
開發者ID:eastee,項目名稱:rebreakcaptcha,代碼行數:14,代碼來源:rebreakcaptcha.py

示例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") 
開發者ID:MycroftAI,項目名稱:personal-backend,代碼行數:6,代碼來源:tts.py

示例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) 
開發者ID:indrajithi,項目名稱:mgc-django,代碼行數:35,代碼來源:feature.py

示例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 
開發者ID:microsoft,項目名稱:macaw,代碼行數:7,代碼來源:speech_recognition.py


注:本文中的pydub.AudioSegment.from_mp3方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。