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


Python AudioSegment.from_file方法代碼示例

本文整理匯總了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: prepro_audio

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def prepro_audio(source_path, target_path, format=None, sr=None, db=None):
    """
    Read a wav, change sample rate, format, and average decibel and write to target path.
    :param source_path: source wav file path
    :param target_path: target wav file path
    :param sr: sample rate.
    :param format: output audio format.
    :param db: decibel.
    """
    sound = AudioSegment.from_file(source_path, format)
    if sr:
        sound = sound.set_frame_rate(sr)
    if db:
        change_dBFS = db - sound.dBFS
        sound = sound.apply_gain(change_dBFS)
    sound.export(target_path, 'wav') 
開發者ID:andabi,項目名稱:parallel-wavenet-vocoder,代碼行數:18,代碼來源:audio.py

示例2: audioToSpectrogram

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def audioToSpectrogram(self, file, pixel_per_sec, height):

        noise_file_index = random.randint(1, 190)
        noise_file_name = "/data/tom/backgroundmusic/normalized-background_{}.wav".format(noise_file_index)

        with tempfile.NamedTemporaryFile(suffix='.wav') as noisy_speech_file:

            noise = AudioSegment.from_file(noise_file_name)
            speech = AudioSegment.from_file(file)

            #speech.apply_gain(noise.dBFS - speech.dBFS)

            noisy_speech = speech.overlay(noise - 5, loop=True)
            noisy_speech.export(noisy_speech_file.name, format="wav")

            # shutil.copyfile(noisy_speech_file.name, os.path.join("/extra/tom/news2/debug", "mixed_" + os.path.basename(noisy_speech_file.name)))

            with tempfile.NamedTemporaryFile(suffix='.png') as image_file:
                command = "{} -n remix 1 rate 10k spectrogram -y {} -X {} -m -r -o {}". format(noisy_speech_file.name, height, pixel_per_sec, image_file.name)
                sox.core.sox([command])

                # spectrogram can be inspected at image_file.name
                image = Image.open(image_file.name)

                return np.array(image) 
開發者ID:HPI-DeepLearning,項目名稱:crnn-lid,代碼行數:27,代碼來源:MusicBackgroundSpectrogramGenerator.py

示例3: audioToSpectrogram

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def audioToSpectrogram(self, file, pixel_per_sec, height):

        noise_file_index = random.randint(1, len(NOISE_FILES_LENGTH))
        noise_file_name = "vinyl_noise/normalized-noise{}.wav".format(noise_file_index)

        with tempfile.NamedTemporaryFile(suffix='.wav') as noisy_speech_file:

            noise = AudioSegment.from_file(noise_file_name)
            speech = AudioSegment.from_file(file)

            speech.apply_gain(noise.dBFS - speech.dBFS)

            noisy_speech = speech.overlay(noise - 10, loop=True)
            noisy_speech.export(noisy_speech_file.name, format="wav")

            # shutil.copyfile(noisy_speech_file.name, os.path.join("/extra/tom/news2/debug", "mixed_" + os.path.basename(noisy_speech_file.name)))

            with tempfile.NamedTemporaryFile(suffix='.png') as image_file:
                command = "{} -n remix 1 rate 10k spectrogram -y {} -X {} -m -r -o {}". format(noisy_speech_file.name, height, pixel_per_sec, image_file.name)
                sox.core.sox([command])

                # spectrogram can be inspected at image_file.name
                image = Image.open(image_file.name)

                return np.array(image) 
開發者ID:HPI-DeepLearning,項目名稱:crnn-lid,代碼行數:27,代碼來源:VinylBackgroundSpectrogramGenerator.py

示例4: read_audio_generic

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def read_audio_generic(input_file):
    """
    Function to read audio files with the following extensions
    [".mp3", ".wav", ".au", ".ogg"]
    """
    sampling_rate = -1
    signal = np.array([])
    try:
        audiofile = AudioSegment.from_file(input_file)
        data = np.array([])
        if audiofile.sample_width == 2:
            data = numpy.fromstring(audiofile._data, numpy.int16)
        elif audiofile.sample_width == 4:
            data = numpy.fromstring(audiofile._data, numpy.int32)

        if data.size > 0:
            sampling_rate = audiofile.frame_rate
            temp_signal = []
            for chn in list(range(audiofile.channels)):
                temp_signal.append(data[chn::audiofile.channels])
            signal = numpy.array(temp_signal).T
    except:
        print("Error: file not found or other I/O error. (DECODING FAILED)")
    return sampling_rate, signal 
開發者ID:tyiannak,項目名稱:pyAudioAnalysis,代碼行數:26,代碼來源:audioBasicIO.py

示例5: decodeAudio

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def decodeAudio(filething):
    if hasattr(filething, 'seek'):
        filething.seek(0)
        filecontents = filething.read()
        data, properties = bard_audiofile.decode(data=filecontents)
    else:
        data, properties = bard_audiofile.decode(path=filething)

    if config['enable_internal_checks']:
        FILES_PYDUB_CANT_DECODE_RIGHT = \
            ['/mnt/DD8/media/mp3/id13/k3/software_libre-hq.ogg']
        if hasattr(filething, 'seek'):
            filething.seek(0)
        audio_segment = AudioSegment.from_file(filething)
        if (audio_segment.raw_data != data and
                filething not in FILES_PYDUB_CANT_DECODE_RIGHT):
            with open('/tmp/decoded-song-pydub.raw', 'wb') as f:
                f.write(audio_segment.raw_data)
            with open('/tmp/decoded-song-bard_audiofile.raw', 'wb') as f:
                f.write(data)
            raise Exception('DECODED AUDIO IS DIFFERENT BETWEEN '
                            'BARD_AUDIOFILE AND PYDUB')
        print('bard_audiofile/pydub decode check ' +
              TerminalColors.Ok + 'OK' + TerminalColors.ENDC)
    return data, DecodedAudioPropertiesTupleFromDict(properties) 
開發者ID:antlarr,項目名稱:bard,代碼行數:27,代碼來源:utils.py

示例6: calculateSilences

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def calculateSilences(self, threshold=None, min_length=None):
        try:
            audio_segment = AudioSegment.from_file(self.path())
        except PydubException as exc:
            print('Error processing:', self.path(), ':', exc)
            raise
        self._audioSha256sum = calculateSHA256_data(audio_segment.raw_data)
        thr = threshold or Song.silence_threshold
        minlen = min_length or Song.min_silence_length
        silences = detect_silence_at_beginning_and_end(audio_segment,
                                                       min_silence_len=minlen,
                                                       silence_thresh=thr)
        if silences:
            silence1, silence2 = silences
            self._silenceAtStart = (silence1[1] - silence1[0]) / 1000
            self._silenceAtEnd = (silence2[1] - silence2[0]) / 1000 
開發者ID:antlarr,項目名稱:bard,代碼行數:18,代碼來源:song.py

示例7: makechunks

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def makechunks(path):
    folders=glob.glob(path+'*')
    for folder in folders:
      waves = glob.glob(folder+'/'+ '*.wav')
      print ('w',waves)
      if len(waves) == 0:
          return 10
      for i in waves:
          w = i
          myaudio = AudioSegment.from_file(i, 'wav')
          chunk_length_ms = 20000
          chunks = make_chunks(myaudio, chunk_length_ms)
          print (chunks)
          for i, chunk in enumerate(chunks):
              chunk_name = w.split('.')[0] + "chunk{0}.wav".format(i)
              print (chunk_name)
              print ("exporting", chunk_name)
              chunk.export(folder+'/'+chunk_name, format="wav") 
開發者ID:iamvishnuks,項目名稱:AudioNet,代碼行數:20,代碼來源:data_maker.py

示例8: reset_media

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def reset_media(self):
        """Resets the media to the currently playing song."""
        audio_file = self.player.currentMedia().canonicalUrl().path()
        if os.name == 'nt' and audio_file.startswith('/'):
            audio_file = audio_file[1:]
        if audio_file:
            try:
                self.song = AudioSegment.from_file(audio_file).set_channels(1)
            except PermissionError:
                self.start_animate = False
            else:
                self.samples = np.array(self.song.get_array_of_samples())

                self.max_sample = self.samples.max()
                self.maximum_amp = self.max_sample // 4
                self.points = np.zeros(self.resolution)
                self.start_animate = True
        else:
            self.start_animate = False 
開發者ID:python-discord,項目名稱:code-jam-5,代碼行數:21,代碼來源:fft_analyser.py

示例9: read

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def read(filename, limit=None):
    """
    Reads any file supported by pydub (ffmpeg) and returns the data contained
    within. If file reading fails due to input being a 24-bit wav file,
    wavio is used as a backup.

    Can be optionally limited to a certain amount of seconds from the start
    of the file by specifying the `limit` parameter. This is the amount of
    seconds from the start of the file.

    returns: (channels, samplerate)
    """
    # pydub does not support 24-bit wav files, use wavio when this occurs
    try:
        audiofile = AudioSegment.from_file(filename)

        if limit:
            audiofile = audiofile[:limit * 1000]

        data = np.fromstring(audiofile._data, np.int16)

        channels = []
        for chn in xrange(audiofile.channels):
            channels.append(data[chn::audiofile.channels])

        fs = audiofile.frame_rate
    except audioop.error:
        fs, _, audiofile = wavio.readwav(filename)

        if limit:
            audiofile = audiofile[:limit * 1000]

        audiofile = audiofile.T
        audiofile = audiofile.astype(np.int16)

        channels = []
        for chn in audiofile:
            channels.append(chn)

    return channels, audiofile.frame_rate, unique_hash(filename) 
開發者ID:CwbhX,項目名稱:Jamais-Vu,代碼行數:42,代碼來源:decoder.py

示例10: get_length_audio

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def get_length_audio(audiopath, extension):
    """
    Returns length of audio in seconds.
    Returns None if format isn't supported or in case of error.
    """
    try:
        audio = AudioSegment.from_file(audiopath, extension.replace(".", ""))
    except:
        print "Error in get_length_audio(): %s" % traceback.format_exc()
        return None
    return int(len(audio) / 1000.0) 
開發者ID:CwbhX,項目名稱:Jamais-Vu,代碼行數:13,代碼來源:testing.py

示例11: load_audio_file

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [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

示例12: parse_audio

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def parse_audio(self):
    limit = None
    # limit = 10

    songname, extension = os.path.splitext(os.path.basename(self.filename))

    try:
      audiofile = AudioSegment.from_file(self.filename)

      if limit:
        audiofile = audiofile[:limit * 1000]

      data = np.fromstring(audiofile._data, np.int16)

      channels = []
      for chn in xrange(audiofile.channels):
        channels.append(data[chn::audiofile.channels])

      fs = audiofile.frame_rate
    except audioop.error:
      print('audioop.error')
      pass
        # fs, _, audiofile = wavio.readwav(filename)

        # if limit:
        #     audiofile = audiofile[:limit * 1000]

        # audiofile = audiofile.T
        # audiofile = audiofile.astype(np.int16)

        # channels = []
        # for chn in audiofile:
        #     channels.append(chn)

    return {
      "songname": songname,
      "extension": extension,
      "channels": channels,
      "Fs": audiofile.frame_rate,
      "file_hash": self.parse_file_hash()
    } 
開發者ID:itspoma,項目名稱:audio-fingerprint-identifying-python,代碼行數:43,代碼來源:reader_file.py

示例13: test_import

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def test_import(self):
        sound = AudioSegment.from_file('/input/tests/data/test.wav')

        self.assertEqual(1810, len(sound)) 
開發者ID:Kaggle,項目名稱:docker-python,代碼行數:6,代碼來源:test_pydub.py

示例14: convert_to_music

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [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

示例15: _speak

# 需要導入模塊: from pydub import AudioSegment [as 別名]
# 或者: from pydub.AudioSegment import from_file [as 別名]
def _speak(self, file: Path, session: DialogSession):
		SuperManager.getInstance().mqttManager.playSound(
			soundFilename=file.stem,
			location=file.parent,
			sessionId=session.sessionId,
			siteId=session.siteId
		)

		duration = round(len(AudioSegment.from_file(file)) / 1000, 2)
		SuperManager.getInstance().threadManager.doLater(interval=duration + 0.1, func=self._sayFinished, args=[session]) 
開發者ID:project-alice-assistant,項目名稱:ProjectAlice,代碼行數:12,代碼來源:TTS.py


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