Changeset 633400d for python/demos


Ignore:
Timestamp:
Dec 5, 2018, 10:34:39 PM (6 years ago)
Author:
Paul Brossier <piem@piem.org>
Branches:
feature/cnn, feature/crepe, feature/pitchshift, feature/timestretch, fix/ffmpeg5, master
Children:
283a619a
Parents:
5b46bc3 (diff), f19db54 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' into feature/pitchshift

Location:
python/demos
Files:
7 added
7 edited

Legend:

Unmodified
Added
Removed
  • python/demos/demo_bpm_extract.py

    r5b46bc3 r633400d  
    44from numpy import median, diff
    55
    6 def get_file_bpm(path, params = None):
     6def get_file_bpm(path, params=None):
    77    """ Calculate the beats per minute (bpm) of a given file.
    88        path: path to the file
     
    1111    if params is None:
    1212        params = {}
    13     try:
    14         win_s = params['win_s']
    15         samplerate = params['samplerate']
    16         hop_s = params['hop_s']
    17     except KeyError:
    18         """
    19         # super fast
    20         samplerate, win_s, hop_s = 4000, 128, 64
    21         # fast
    22         samplerate, win_s, hop_s = 8000, 512, 128
    23         """
    24         # default:
    25         samplerate, win_s, hop_s = 44100, 1024, 512
     13    # default:
     14    samplerate, win_s, hop_s = 44100, 1024, 512
     15    if 'mode' in params:
     16        if params.mode in ['super-fast']:
     17            # super fast
     18            samplerate, win_s, hop_s = 4000, 128, 64
     19        elif params.mode in ['fast']:
     20            # fast
     21            samplerate, win_s, hop_s = 8000, 512, 128
     22        elif params.mode in ['default']:
     23            pass
     24        else:
     25            raise ValueError("unknown mode {:s}".format(params.mode))
     26    # manual settings
     27    if 'samplerate' in params:
     28        samplerate = params.samplerate
     29    if 'win_s' in params:
     30        win_s = params.win_s
     31    if 'hop_s' in params:
     32        hop_s = params.hop_s
    2633
    2734    s = source(path, samplerate, hop_s)
     
    4552            break
    4653
    47     # Convert to periods and to bpm
    48     if len(beats) > 1:
    49         if len(beats) < 4:
    50             print("few beats found in {:s}".format(path))
    51         bpms = 60./diff(beats)
    52         b = median(bpms)
    53     else:
    54         b = 0
    55         print("not enough beats found in {:s}".format(path))
    56     return b
     54    def beats_to_bpm(beats, path):
     55        # if enough beats are found, convert to periods then to bpm
     56        if len(beats) > 1:
     57            if len(beats) < 4:
     58                print("few beats found in {:s}".format(path))
     59            bpms = 60./diff(beats)
     60            return median(bpms)
     61        else:
     62            print("not enough beats found in {:s}".format(path))
     63            return 0
     64
     65    return beats_to_bpm(beats, path)
    5766
    5867if __name__ == '__main__':
    59     import sys
    60     for f in sys.argv[1:]:
    61         bpm = get_file_bpm(f)
     68    import argparse
     69    parser = argparse.ArgumentParser()
     70    parser.add_argument('-m', '--mode',
     71            help="mode [default|fast|super-fast]",
     72            dest="mode", default='default')
     73    parser.add_argument('sources',
     74            nargs='+',
     75            help="input_files")
     76    args = parser.parse_args()
     77    for f in args.sources:
     78        bpm = get_file_bpm(f, params = args)
    6279        print("{:6s} {:s}".format("{:2f}".format(bpm), f))
  • python/demos/demo_filter.py

    r5b46bc3 r633400d  
    11#! /usr/bin/env python
    22
     3import sys
     4import os.path
     5import aubio
    36
    4 def apply_filter(path):
    5     from aubio import source, sink, digital_filter
    6     from os.path import basename, splitext
    77
     8def apply_filter(path, target):
    89    # open input file, get its samplerate
    9     s = source(path)
     10    s = aubio.source(path)
    1011    samplerate = s.samplerate
    1112
    1213    # create an A-weighting filter
    13     f = digital_filter(7)
     14    f = aubio.digital_filter(7)
    1415    f.set_a_weighting(samplerate)
    15     # alternatively, apply another filter
    1616
    1717    # create output file
    18     o = sink("filtered_" + splitext(basename(path))[0] + ".wav", samplerate)
     18    o = aubio.sink(target, samplerate)
    1919
    2020    total_frames = 0
    2121    while True:
     22        # read from source
    2223        samples, read = s()
     24        # filter samples
    2325        filtered_samples = f(samples)
     26        # write to sink
    2427        o(filtered_samples, read)
     28        # count frames read
    2529        total_frames += read
    26         if read < s.hop_size: break
     30        # end of file reached
     31        if read < s.hop_size:
     32            break
    2733
     34    # print some info
    2835    duration = total_frames / float(samplerate)
    29     print ("read {:s}".format(s.uri))
    30     print ("applied A-weighting filtered ({:d} Hz)".format(samplerate))
    31     print ("wrote {:s} ({:.2f} s)".format(o.uri, duration))
     36    input_str = "input: {:s} ({:.2f} s, {:d} Hz)"
     37    output_str = "output: {:s}, A-weighting filtered ({:d} frames total)"
     38    print(input_str.format(s.uri, duration, samplerate))
     39    print(output_str.format(o.uri, total_frames))
    3240
    3341if __name__ == '__main__':
    34     import sys
    35     for f in sys.argv[1:]:
    36         apply_filter(f)
     42    usage = "{:s} <input_file> [output_file]".format(sys.argv[0])
     43    if not 1 < len(sys.argv) < 4:
     44        print(usage)
     45        sys.exit(1)
     46    if len(sys.argv) < 3:
     47        input_path = sys.argv[1]
     48        basename = os.path.splitext(os.path.basename(input_path))[0] + ".wav"
     49        output_path = "filtered_" + basename
     50    else:
     51        input_path, output_path = sys.argv[1:]
     52    # run function
     53    apply_filter(input_path, output_path)
  • python/demos/demo_filterbank.py

    r5b46bc3 r633400d  
    11#! /usr/bin/env python
    22
    3 from aubio import filterbank, fvec
    4 from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title
    5 from numpy import vstack, arange
     3"""Create a filterbank from a list of frequencies.
    64
     5This demo uses `aubio.filterbank.set_triangle_bands` to build a set of
     6triangular filters from a list of frequencies.
     7
     8The filterbank coefficients are then modified before being displayed."""
     9
     10import aubio
     11import numpy as np
     12import matplotlib.pyplot as plt
     13
     14# sampling rate and size of the fft
     15samplerate = 48000
    716win_s = 2048
    8 samplerate = 48000
    917
     18# define a list of custom frequency
    1019freq_list = [60, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 24000]
     20# number of filters to create
    1121n_filters = len(freq_list) - 2
    1222
    13 f = filterbank(n_filters, win_s)
    14 freqs = fvec(freq_list)
     23# create a new filterbank
     24f = aubio.filterbank(n_filters, win_s)
     25freqs = aubio.fvec(freq_list)
    1526f.set_triangle_bands(freqs, samplerate)
    1627
     28# get the coefficients from the filterbank
    1729coeffs = f.get_coeffs()
    18 coeffs[4] *= 5.
    19 
     30# apply a gain to fifth band
     31coeffs[4] *= 6.
     32# load the modified coeffs into the filterbank
    2033f.set_coeffs(coeffs)
    2134
    22 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    23 title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.')
    24 loglog(times.T, f.get_coeffs().T, '.-')
    25 xlim([50, samplerate/2])
    26 ylim([1.0e-6, 2.0e-2])
    27 xlabel('log frequency (Hz)')
    28 ylabel('log amplitude')
    29 
    30 show()
     35# display the band gains in a loglog plot
     36freqs = np.vstack([np.arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
     37plt.title('filterbank built from a list of frequencies\n'
     38          'The 5th band has been amplified by a factor 6.')
     39plt.loglog(freqs.T, f.get_coeffs().T, '.-')
     40plt.xlim([50, samplerate/2])
     41plt.ylim([1.0e-6, 2.0e-2])
     42plt.xlabel('log frequency (Hz)')
     43plt.ylabel('log amplitude')
     44plt.show()
  • python/demos/demo_pitch_sinusoid.py

    r5b46bc3 r633400d  
    3838pointer += partition
    3939pointer += partition
    40 freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length/8)
     40freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length//8)
    4141
    4242a = build_sinusoid(sin_length, freqs, samplerate)
  • python/demos/demo_source_simple.py

    r5b46bc3 r633400d  
    11#! /usr/bin/env python
    2 import sys, aubio
     2
     3"""A simple example using aubio.source."""
     4
     5import sys
     6import aubio
    37
    48samplerate = 0  # use original source samplerate
    5 hop_size = 256 # number of frames to read in one block
    6 s = aubio.source(sys.argv[1], samplerate, hop_size)
     9hop_size = 256  # number of frames to read in one block
     10src = aubio.source(sys.argv[1], samplerate, hop_size)
    711total_frames = 0
    812
    9 while True: # reading loop
    10     samples, read = s()
    11     total_frames += read
    12     if read < hop_size: break # end of file reached
     13while True:
     14    samples, read = src()  # read hop_size new samples from source
     15    total_frames += read   # increment total number of frames
     16    if read < hop_size:    # end of file reached
     17        break
    1318
    1419fmt_string = "read {:d} frames at {:d}Hz from {:s}"
    15 print (fmt_string.format(total_frames, s.samplerate, sys.argv[1]))
    16 
     20print(fmt_string.format(total_frames, src.samplerate, src.uri))
  • python/demos/demo_timestretch.py

    r5b46bc3 r633400d  
    1313
    1414win_s = 1024
    15 hop_s = win_s / 8 # 87.5 % overlap
     15hop_s = win_s // 8 # 87.5 % overlap
    1616
    1717warmup = win_s // hop_s - 1
  • python/demos/demo_timestretch_online.py

    r5b46bc3 r633400d  
    1212import numpy as np
    1313
    14 win_s = 1024
    15 hop_s = win_s / 8 # 87.5 % overlap
     14win_s = 512
     15hop_s = win_s // 8 # 87.5 % overlap
    1616
    1717warmup = win_s // hop_s - 1
     
    9393    old_grain.phas = np.copy(cur_grain.phas)
    9494
     95    # until end of file
     96    if read < hop_s: break
     97    # increment block counter
    9598    block_read += 1
    96     if read < hop_s: break
    9799
    98100for t in range(warmup + 2): # purge the last frames from the phase vocoder
Note: See TracChangeset for help on using the changeset viewer.