当前位置: 首页>>代码示例>>Python>>正文


Python librosa.get_duration方法代码示例

本文整理汇总了Python中librosa.get_duration方法的典型用法代码示例。如果您正苦于以下问题:Python librosa.get_duration方法的具体用法?Python librosa.get_duration怎么用?Python librosa.get_duration使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在librosa的用法示例。


在下文中一共展示了librosa.get_duration方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def __init__(self, file: str, *, sample_rate: int = 44100):
        """        
        Parameters
        ----------
        file
            Audio file to load
        """

        self.file = file
        self.samples, self.sample_rate = librosa.load(file, sr=sample_rate)
        self.duration = librosa.get_duration(y=self.samples, sr=self.sample_rate) 
开发者ID:scherroman,项目名称:mugen,代码行数:13,代码来源:Audio.py

示例2: transform_audio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def transform_audio(self, y):
        '''Compute the tempogram

        Parameters
        ----------
        y : np.ndarray
            Audio buffer

        Returns
        -------
        data : dict
            data['tempogram'] : np.ndarray, shape=(n_frames, win_length)
                The tempogram
        '''
        n_frames = self.n_frames(get_duration(y=y, sr=self.sr))

        tgram = tempogram(y=y, sr=self.sr,
                          hop_length=self.hop_length,
                          win_length=self.win_length)

        tgram = to_dtype(fix_length(tgram, n_frames), self.dtype)
        return {'tempogram': tgram.T[self.idx]} 
开发者ID:bmcfee,项目名称:pumpp,代码行数:24,代码来源:rhythm.py

示例3: test_ir_convolution

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def test_ir_convolution(ir_files,jam_fixture,n_fft,rolloff_value):
    D = muda.deformers.IRConvolution(ir_files = ir_files, n_fft=n_fft, rolloff_value = rolloff_value)

    jam_orig = deepcopy(jam_fixture)
    orig_duration = librosa.get_duration(**jam_orig.sandbox.muda['_audio'])

    for jam_new in D.transform(jam_orig):
        # Verify that the original jam reference hasn't changed
        assert jam_new is not jam_orig

        #Testing with shifted impulse
        __test_shifted_impulse(jam_orig, jam_new, ir_files, orig_duration,n_fft=n_fft, rolloff_value = rolloff_value)

        #Verify that the state and history objects are intact
        __test_deformer_history(D, jam_new.sandbox.muda.history[-1])

    # Serialization test
    D2 = muda.deserialize(muda.serialize(D))
    __test_params(D, D2) 
开发者ID:bmcfee,项目名称:muda,代码行数:21,代码来源:test_deformers.py

示例4: test_save

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def test_save(jam_in, audio_file, strict, fmt):

    jam = muda.load_jam_audio(jam_in, audio_file)

    _, jamfile = tempfile.mkstemp(suffix='.jams')
    _, audfile = tempfile.mkstemp(suffix='.wav')

    muda.save(audfile, jamfile, jam, strict=strict, fmt=fmt)

    jam2 = muda.load_jam_audio(jamfile, audfile, fmt=fmt)
    jam2_raw = jams.load(jamfile, fmt=fmt)

    os.unlink(audfile)
    os.unlink(jamfile)

    assert hasattr(jam2.sandbox, 'muda')
    assert '_audio' in jam2.sandbox.muda
    assert '_audio' not in jam2_raw.sandbox.muda

    duration = librosa.get_duration(**jam2.sandbox.muda['_audio'])

    assert jam2.file_metadata.duration == duration 
开发者ID:bmcfee,项目名称:muda,代码行数:24,代码来源:test_core.py

示例5: audio_files_to_numpy

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def audio_files_to_numpy(audio_dir, list_audio_files, sample_rate, frame_length, hop_length_frame, min_duration):
    """This function take audio files of a directory and merge them
    in a numpy matrix of size (nb_frame,frame_length) for a sliding window of size hop_length_frame"""

    list_sound_array = []

    for file in list_audio_files:
        # open the audio file
        y, sr = librosa.load(os.path.join(audio_dir, file), sr=sample_rate)
        total_duration = librosa.get_duration(y=y, sr=sr)

        if (total_duration >= min_duration):
            list_sound_array.append(audio_to_audio_frame_stack(
                y, frame_length, hop_length_frame))
        else:
            print(
                f"The following file {os.path.join(audio_dir,file)} is below the min duration")

    return np.vstack(list_sound_array) 
开发者ID:vbelz,项目名称:Speech-enhancement,代码行数:21,代码来源:data_tools.py

示例6: audio_dur

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def audio_dur(path, ext='', root=''):
    path = os.path.join(root, '{}{}'.format(path, ext))
    try:
        return lr.get_duration(filename=path)
    except Exception as ex:        
        print_err('could not read {}\n{}'.format(path, ex))
        return 0 
开发者ID:hcmlab,项目名称:vadnet,代码行数:9,代码来源:utils.py

示例7: randomPositionInAudio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def randomPositionInAudio(audio_path, duration):
    length = librosa.get_duration(filename=audio_path)
    if duration >= length:
        return 0.0, None
    else:
        offset = np.random.uniform() * (length - duration)
        return offset, duration 
开发者ID:Veleslavia,项目名称:vimss,代码行数:9,代码来源:Input.py

示例8: transform_audio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def transform_audio(self, y):
        '''Compute the time position encoding

        Parameters
        ----------
        y : np.ndarray
            Audio buffer

        Returns
        -------
        data : dict
            data['relative'] = np.ndarray, shape=(n_frames, 2)
            data['absolute'] = np.ndarray, shape=(n_frames, 2)

                Relative and absolute time positional encodings.
        '''

        duration = get_duration(y=y, sr=self.sr)
        n_frames = self.n_frames(duration)

        relative = np.zeros((n_frames, 2), dtype=np.float32)
        relative[:, 0] = np.cos(np.pi * np.linspace(0, 1, num=n_frames))
        relative[:, 1] = np.sin(np.pi * np.linspace(0, 1, num=n_frames))

        absolute = relative * np.sqrt(duration)

        return {'relative': to_dtype(relative[self.idx], self.dtype),
                'absolute': to_dtype(absolute[self.idx], self.dtype)} 
开发者ID:bmcfee,项目名称:pumpp,代码行数:30,代码来源:time.py

示例9: transform_audio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def transform_audio(self, y):
        '''Compute the STFT magnitude and phase.

        Parameters
        ----------
        y : np.ndarray
            The audio buffer

        Returns
        -------
        data : dict
            data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
                STFT magnitude

            data['phase'] : np.ndarray, shape=(n_frames, 1 + n_fft//2)
                STFT phase
        '''
        n_frames = self.n_frames(get_duration(y=y, sr=self.sr))

        D = stft(y, hop_length=self.hop_length,
                 n_fft=self.n_fft)

        D = fix_length(D, n_frames)

        mag, phase = magphase(D)
        if self.log:
            mag = amplitude_to_db(mag, ref=np.max)

        return {'mag': to_dtype(mag.T[self.idx], self.dtype),
                'phase': to_dtype(np.angle(phase.T)[self.idx], self.dtype)} 
开发者ID:bmcfee,项目名称:pumpp,代码行数:32,代码来源:fft.py

示例10: transform_audio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def transform_audio(self, y):
        '''Compute the CQT

        Parameters
        ----------
        y : np.ndarray
            The audio buffer

        Returns
        -------
        data : dict
            data['mag'] : np.ndarray, shape = (n_frames, n_bins)
                The CQT magnitude

            data['phase']: np.ndarray, shape = mag.shape
                The CQT phase
        '''
        n_frames = self.n_frames(get_duration(y=y, sr=self.sr))

        C = cqt(y=y, sr=self.sr, hop_length=self.hop_length,
                fmin=self.fmin,
                n_bins=(self.n_octaves * self.over_sample * 12),
                bins_per_octave=(self.over_sample * 12))

        C = fix_length(C, n_frames)

        cqtm, phase = magphase(C)
        if self.log:
            cqtm = amplitude_to_db(cqtm, ref=np.max)

        return {'mag': to_dtype(cqtm.T[self.idx], self.dtype),
                'phase': to_dtype(np.angle(phase).T[self.idx], self.dtype)} 
开发者ID:bmcfee,项目名称:pumpp,代码行数:34,代码来源:cqt.py

示例11: transform_audio

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def transform_audio(self, y):
        '''Compute the Mel spectrogram

        Parameters
        ----------
        y : np.ndarray
            The audio buffer

        Returns
        -------
        data : dict
            data['mag'] : np.ndarray, shape=(n_frames, n_mels)
                The Mel spectrogram
        '''
        n_frames = self.n_frames(get_duration(y=y, sr=self.sr))

        mel = np.sqrt(melspectrogram(y=y, sr=self.sr,
                                     n_fft=self.n_fft,
                                     hop_length=self.hop_length,
                                     n_mels=self.n_mels,
                                     fmax=self.fmax))

        mel = fix_length(mel, n_frames)

        if self.log:
            mel = amplitude_to_db(mel, ref=np.max)

        # Type convert
        mel = to_dtype(mel, self.dtype)

        return {'mag': mel.T[self.idx]} 
开发者ID:bmcfee,项目名称:pumpp,代码行数:33,代码来源:mel.py

示例12: stat_acoustic

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def stat_acoustic():
    print("\nAcoustic Data:")
    wav_folder = join(ROOT_FOLDER, "data", "vlsp", "wav")
    files = listdir(wav_folder)
    files = [join(wav_folder, file) for file in files]
    durations = [librosa.get_duration(filename=file) for file in files]
    durations = pd.Series(durations)
    print(f"Total: {durations.sum():.2f} seconds ({durations.sum() / 3600:.2f} hours)")
    print(durations.describe()) 
开发者ID:undertheseanlp,项目名称:automatic_speech_recognition,代码行数:11,代码来源:eda_vlsp.py

示例13: predict

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def predict(self, filename=None, y=None, sr=None, outputs=None):
        '''Predict annotations

        Parameters
        ----------
        filename : str (optional)
            Path to audio file

        y, sr : (optional)
            Audio buffer and sample rate

        outputs : (optional)
            Pre-computed model outputs as produced by `CremaModel.outputs`.
            If provided, then predictions are derived from these instead of
            `filename` or `(y, sr)`.


        .. note:: At least one of `filename`, `y, sr` must be provided.

        Returns
        -------
        jams.Annotation
            The predicted annotation
        '''

        # Pump the input features
        output_key = self.model.output_names[0]

        if outputs is None:
            outputs = self.outputs(filename=filename, y=y, sr=sr)

        # Invert the prediction.  This is always the first output layer.
        ann = self.pump[output_key].inverse(outputs[output_key])

        # Populate the metadata
        ann.annotation_metadata.version = self.version
        ann.annotation_metadata.annotation_tools = 'CREMA {}'.format(version)
        ann.annotation_metadata.data_source = 'program'
        ann.duration = librosa.get_duration(y=y, sr=sr, filename=filename)

        return ann 
开发者ID:bmcfee,项目名称:crema,代码行数:43,代码来源:base.py

示例14: duration_in_s

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def duration_in_s(self) -> float:
        try:
            return librosa.get_duration(filename=str(self.audio_file))
        except Exception as e:
            log("Failed to get duration of {}: {}".format(self.audio_file, e))
            return 0 
开发者ID:JuliusKunze,项目名称:speechless,代码行数:8,代码来源:labeled_example.py

示例15: get_duration

# 需要导入模块: import librosa [as 别名]
# 或者: from librosa import get_duration [as 别名]
def get_duration(self, filename, sr):  #pylint: disable=invalid-name
    ''' time in second '''
    if filename.endswith('.npy'):
      nframe = np.load(filename).shape[0]
      return librosa.frames_to_time(
          nframe, hop_length=self._winstep * sr, sr=sr)

    if filename.endswith('.wav'):
      return librosa.get_duration(filename=filename)

    raise ValueError("filename suffix not .npy or .wav: {}".format(
        os.path.splitext(filename)[-1])) 
开发者ID:didi,项目名称:delta,代码行数:14,代码来源:speech_cls_task.py


注:本文中的librosa.get_duration方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。