audiosegment.py
def filter_bank(self, lower_bound_hz=50, upper_bound_hz=8E3, nfilters=128, mode='mel'):
        """
        Returns a numpy array of shape (nfilters, nsamples), where each
        row of data is the result of bandpass filtering the audiosegment
        around a particular frequency. The frequencies are
        spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with
        the np array. The particular spacing of the frequencies depends on `mode`,
        which can be either: 'linear', 'mel', or 'log'.

        .. note:: This method is an approximation of a gammatone filterbank
                  until I get around to writing an actual gammatone filterbank
                  function.

        .. code-block:: python

            # Example usage
            import audiosegment
            import matplotlib.pyplot as plt
            import numpy as np

            def visualize(spect, frequencies, title=""):
                # Visualize the result of calling seg.filter_bank() for any number of filters
                i = 0
                for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])):
                    plt.subplot(spect.shape[0], 1, index + 1)
                    if i == 0:
                        plt.title(title)
                        i += 1
                    plt.ylabel("{0:.0f}".format(freq))
                    plt.plot(row)
                plt.show()

            seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1)
            spec, frequencies = seg.filter_bank(nfilters=5)
            visualize(spec, frequencies)

        .. image:: images/filter_bank.png

        :param lower_bound_hz:  The lower bound of the frequencies to use in the bandpass filters.
        :param upper_bound_hz:  The upper bound of the frequencies to use in the bandpass filters.
        :param nfilters:        The number of filters to apply. This will determine which frequencies
                                are used as well, as they are interpolated between
                                `lower_bound_hz` and `upper_bound_hz` based on `mode`.
        :param mode:            The way the frequencies are spaced. Options are: `linear`, in which case
                                the frequencies are linearly interpolated between `lower_bound_hz` and
                                `upper_bound_hz`, `mel`, in which case the mel frequencies are used,
                                or `log`, in which case they are log-10 spaced.
        :returns:               A numpy array of the form (nfilters, nsamples), where each row is the
                                audiosegment, bandpass-filtered around a particular frequency,
                                and the list of frequencies. I.e., returns (spec, freqs).
        """
        # Logspace to get all the frequency channels we are after
        data = self.to_numpy_array()
        if mode.lower() == 'mel':
            frequencies = librosa.core.mel_frequencies(n_mels=nfilters, fmin=lower_bound_hz, fmax=upper_bound_hz)
        elif mode.lower() == 'linear':
            frequencies = np.linspace(lower_bound_hz, upper_bound_hz, num=nfilters, endpoint=True)
        elif mode.lower() == 'log':
            start = np.log10(lower_bound_hz)
            stop = np.log10(upper_bound_hz)
            frequencies = np.logspace(start, stop, num=nfilters, endpoint=True, base=10.0)
        else:
            raise ValueError("'mode' must be one of: (mel, linear, or log), but was {}".format(mode))

        # Do a band-pass filter in each frequency
        rows = [filters.bandpass_filter(data, freq*0.8, freq*1.2, self.frame_rate) for freq in frequencies]
        rows = np.array(rows)
        spect = np.vstack(rows)
        return spect, frequencies
def filter_bank(self, lower_bound_hz=50, upper_bound_hz=8E3, nfilters=128, mode='mel'):
        """
        Returns a numpy array of shape (nfilters, nsamples), where each
        row of data is the result of bandpass filtering the audiosegment
        around a particular frequency. The frequencies are
        spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with
        the np array. The particular spacing of the frequencies depends on `mode`,
        which can be either: 'linear', 'mel', or 'log'.

        .. note:: This method is an approximation of a gammatone filterbank
                  until I get around to writing an actual gammatone filterbank
                  function.

        .. code-block:: python

            # Example usage
            import audiosegment
            import matplotlib.pyplot as plt
            import numpy as np

            def visualize(spect, frequencies, title=""):
                # Visualize the result of calling seg.filter_bank() for any number of filters
                i = 0
                for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])):
                    plt.subplot(spect.shape[0], 1, index + 1)
                    if i == 0:
                        plt.title(title)
                        i += 1
                    plt.ylabel("{0:.0f}".format(freq))
                    plt.plot(row)
                plt.show()

            seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1)
            spec, frequencies = seg.filter_bank(nfilters=5)
            visualize(spec, frequencies)

        .. image:: images/filter_bank.png

        :param lower_bound_hz:  The lower bound of the frequencies to use in the bandpass filters.
        :param upper_bound_hz:  The upper bound of the frequencies to use in the bandpass filters.
        :param nfilters:        The number of filters to apply. This will determine which frequencies
                                are used as well, as they are interpolated between
                                `lower_bound_hz` and `upper_bound_hz` based on `mode`.
        :param mode:            The way the frequencies are spaced. Options are: `linear`, in which case
                                the frequencies are linearly interpolated between `lower_bound_hz` and
                                `upper_bound_hz`, `mel`, in which case the mel frequencies are used,
                                or `log`, in which case they are log-10 spaced.
        :returns:               A numpy array of the form (nfilters, nsamples), where each row is the
                                audiosegment, bandpass-filtered around a particular frequency,
                                and the list of frequencies. I.e., returns (spec, freqs).
        """
        # Logspace to get all the frequency channels we are after
        data = self.to_numpy_array()
        if mode.lower() == 'mel':
            frequencies = librosa.core.mel_frequencies(n_mels=nfilters, fmin=lower_bound_hz, fmax=upper_bound_hz)
        elif mode.lower() == 'linear':
            frequencies = np.linspace(lower_bound_hz, upper_bound_hz, num=nfilters, endpoint=True)
        elif mode.lower() == 'log':
            start = np.log10(lower_bound_hz)
            stop = np.log10(upper_bound_hz)
            frequencies = np.logspace(start, stop, num=nfilters, endpoint=True, base=10.0)
        else:
            raise ValueError("'mode' must be one of: (mel, linear, or log), but was {}".format(mode))

        # Do a band-pass filter in each frequency
        rows = [filters.bandpass_filter(data, freq*0.8, freq*1.2, self.frame_rate) for freq in frequencies]
        rows = np.array(rows)
        spect = np.vstack(rows)
        return spect, frequencies
Returns a numpy array of shape (nfilters, nsamples), where each
        row of data is the result of bandpass filtering the audiosegment
        around a particular frequency. The frequencies are
        spaced from `lower_bound_hz` to `upper_bound_hz` and are returned with
        the np array. The particular spacing of the frequencies depends on `mode`,
        which can be either: 'linear', 'mel', or 'log'.

        .. note:: This method is an approximation of a gammatone filterbank
                  until I get around to writing an actual gammatone filterbank
                  function.

        .. code-block:: python

            # Example usage
            import audiosegment
            import matplotlib.pyplot as plt
            import numpy as np

            def visualize(spect, frequencies, title=""):
                # Visualize the result of calling seg.filter_bank() for any number of filters
                i = 0
                for freq, (index, row) in zip(frequencies[::-1], enumerate(spect[::-1, :])):
                    plt.subplot(spect.shape[0], 1, index + 1)
                    if i == 0:
                        plt.title(title)
                        i += 1
                    plt.ylabel("{0:.0f}".format(freq))
                    plt.plot(row)
                plt.show()

            seg = audiosegment.from_file("some_audio.wav").resample(sample_rate_Hz=24000, sample_width=2, channels=1)
            spec, frequencies = seg.filter_bank(nfilters=5)
            visualize(spec, frequencies)

        .. image:: images/filter_bank.png

        :param lower_bound_hz:  The lower bound of the frequencies to use in the bandpass filters.
        :param upper_bound_hz:  The upper bound of the frequencies to use in the bandpass filters.
        :param nfilters:        The number of filters to apply. This will determine which frequencies
                                are used as well, as they are interpolated between
                                `lower_bound_hz` and `upper_bound_hz` based on `mode`.
        :param mode:            The way the frequencies are spaced. Options are: `linear`, in which case
                                the frequencies are linearly interpolated between `lower_bound_hz` and
                                `upper_bound_hz`, `mel`, in which case the mel frequencies are used,
                                or `log`, in which case they are log-10 spaced.
        :returns:               A numpy array of the form (nfilters, nsamples), where each row is the
                                audiosegment, bandpass-filtered around a particular frequency,
                                and the list of frequencies. I.e., returns (spec, freqs).