当前位置: 首页>>代码示例>>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;未经允许,请勿转载。