1 | #! /usr/bin/env python |
---|
2 | |
---|
3 | import os |
---|
4 | import glob |
---|
5 | import numpy as np |
---|
6 | from tempfile import mkstemp |
---|
7 | |
---|
8 | DEFAULT_SOUND = '22050Hz_5s_brownnoise.wav' |
---|
9 | |
---|
10 | def array_from_text_file(filename, dtype = 'float'): |
---|
11 | realpathname = os.path.join(os.path.dirname(__file__), filename) |
---|
12 | return np.loadtxt(realpathname, dtype = dtype) |
---|
13 | |
---|
14 | def list_all_sounds(rel_dir): |
---|
15 | datadir = os.path.join(os.path.dirname(__file__), rel_dir) |
---|
16 | return glob.glob(os.path.join(datadir,'*.*')) |
---|
17 | |
---|
18 | def get_default_test_sound(TestCase, rel_dir = 'sounds'): |
---|
19 | all_sounds = list_all_sounds(rel_dir) |
---|
20 | if len(all_sounds) == 0: |
---|
21 | TestCase.skipTest("please add some sounds in \'python/tests/sounds\'") |
---|
22 | else: |
---|
23 | default_sound = all_sounds[0] |
---|
24 | if DEFAULT_SOUND in map(os.path.basename, all_sounds): |
---|
25 | while os.path.basename(default_sound) != DEFAULT_SOUND: |
---|
26 | default_sound = all_sounds.pop(0) |
---|
27 | return default_sound |
---|
28 | |
---|
29 | def get_tmp_sink_path(): |
---|
30 | fd, path = mkstemp() |
---|
31 | os.close(fd) |
---|
32 | return path |
---|
33 | |
---|
34 | def del_tmp_sink_path(path): |
---|
35 | try: |
---|
36 | os.unlink(path) |
---|
37 | except WindowsError as e: |
---|
38 | # removing the temporary directory sometimes fails on windows |
---|
39 | errmsg = "failed deleting temporary file {:s} ({:s})" |
---|
40 | warnings.warn(UserWarning(errmsg.format(path, repr(e)))) |
---|
41 | |
---|
42 | def array_from_yaml_file(filename): |
---|
43 | import yaml |
---|
44 | f = open(filename) |
---|
45 | yaml_data = yaml.safe_load(f) |
---|
46 | f.close() |
---|
47 | return yaml_data |
---|
48 | |
---|
49 | def count_samples_in_file(file_path): |
---|
50 | from aubio import source |
---|
51 | hopsize = 256 |
---|
52 | s = source(file_path, 0, hopsize) |
---|
53 | total_frames = 0 |
---|
54 | while True: |
---|
55 | _, read = s() |
---|
56 | total_frames += read |
---|
57 | if read < hopsize: break |
---|
58 | return total_frames |
---|
59 | |
---|
60 | def count_samples_in_directory(samples_dir): |
---|
61 | total_frames = 0 |
---|
62 | for f in os.walk(samples_dir): |
---|
63 | if len(f[2]): |
---|
64 | for each in f[2]: |
---|
65 | file_path = os.path.join(f[0], each) |
---|
66 | if file_path: |
---|
67 | total_frames += count_samples_in_file(file_path) |
---|
68 | return total_frames |
---|
69 | |
---|
70 | def count_files_in_directory(samples_dir): |
---|
71 | total_files = 0 |
---|
72 | for f in os.walk(samples_dir): |
---|
73 | if len(f[2]): |
---|
74 | for each in f[2]: |
---|
75 | file_path = os.path.join(f[0], each) |
---|
76 | if file_path: |
---|
77 | total_files += 1 |
---|
78 | return total_files |
---|