forked from bendalab/audioio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audioloader.py
1824 lines (1625 loc) · 60.6 KB
/
audioloader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Loading data, metadata, and markers from audio files.
- `load_audio()`: load a whole audio file at once.
- `metadata()`: read metadata of an audio file.
- `markers()`: read markers of an audio file.
- `BufferArray()`: random access to 2D data of which only a part is held in memory.
- `AudioLoader`: read data from audio files in chunks.
- `blocks()`: generator for blockwise processing of array data.
The read in data are always numpy arrays of floats ranging between -1 and 1.
The arrays are 2-D arrays with first axis time and second axis channel,
even for single channel data.
If an audio file cannot be loaded, you might need to install
additional packages. See
[installation](https://bendalab.github.io/audioio/installation) for
further instructions.
For a demo run the module as:
```
python -m audioio.audioloader audiofile.wav
```
"""
import sys
import warnings
import os.path
import numpy as np
from .audiomodules import *
from .riffmetadata import metadata_riff, markers_riff
from .audiometadata import update_gain, add_unwrap
from .audiotools import unwrap
def load_wave(filepath):
"""Load wav file using the wave module from pythons standard libray.
Documentation
-------------
https://docs.python.org/3.8/library/wave.html
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The wave module is not installed
*
Loading of the data failed
"""
if not audio_modules['wave']:
raise ImportError
wf = wave.open(filepath, 'r') # 'with' is not supported by wave
(nchannels, sampwidth, rate, nframes, comptype, compname) = wf.getparams()
buffer = wf.readframes(nframes)
factor = 2.0**(sampwidth*8-1)
if sampwidth == 1:
dtype = 'u1'
buffer = np.frombuffer(buffer, dtype=dtype).reshape(-1, nchannels)
data = buffer.astype('d')/factor - 1.0
else:
dtype = f'i{sampwidth}'
buffer = np.frombuffer(buffer, dtype=dtype).reshape(-1, nchannels)
data = buffer.astype('d')/factor
wf.close()
return data, float(rate)
def load_ewave(filepath):
"""Load wav file using ewave module.
Documentation
-------------
https://github.com/melizalab/py-ewave
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The ewave module is not installed
*
Loading of the data failed
"""
if not audio_modules['ewave']:
raise ImportError
data = np.array([])
rate = 0.0
with ewave.open(filepath, 'r') as wf:
rate = wf.sampling_rate
buffer = wf.read()
data = ewave.rescale(buffer, 'float')
if len(data.shape) == 1:
data = np.reshape(data,(-1, 1))
return data, float(rate)
def load_wavfile(filepath):
"""Load wav file using scipy.io.wavfile.
Documentation
-------------
http://docs.scipy.org/doc/scipy/reference/io.html
Does not support blocked read.
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The scipy.io module is not installed
*
Loading of the data failed
"""
if not audio_modules['scipy.io.wavfile']:
raise ImportError
warnings.filterwarnings("ignore")
rate, data = wavfile.read(filepath)
warnings.filterwarnings("always")
if data.dtype == np.uint8:
data = data / 128.0 - 1.0
elif np.issubdtype(data.dtype, np.signedinteger):
data = data / (2.0**(data.dtype.itemsize*8-1))
else:
data = data.astype(np.float64, copy=False)
if len(data.shape) == 1:
data = np.reshape(data,(-1, 1))
return data, float(rate)
def load_soundfile(filepath):
"""Load audio file using SoundFile (based on libsndfile).
Documentation
-------------
http://pysoundfile.readthedocs.org
http://www.mega-nerd.com/libsndfile
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The soundfile module is not installed.
*
Loading of the data failed.
"""
if not audio_modules['soundfile']:
raise ImportError
data = np.array([])
rate = 0.0
with soundfile.SoundFile(filepath, 'r') as sf:
rate = sf.samplerate
data = sf.read(frames=-1, dtype='float64', always_2d=True)
return data, float(rate)
def load_wavefile(filepath):
"""Load audio file using wavefile (based on libsndfile).
Documentation
-------------
https://github.com/vokimon/python-wavefile
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The wavefile module is not installed.
*
Loading of the data failed.
"""
if not audio_modules['wavefile']:
raise ImportError
rate, data = wavefile.load(filepath)
return data.astype(np.float64, copy=False).T, float(rate)
def load_audioread(filepath):
"""Load audio file using audioread.
Documentation
-------------
https://github.com/beetbox/audioread
Parameters
----------
filepath: string
The full path and name of the file to load.
Returns
-------
data: array
All data traces as an 2-D numpy array, first dimension is time, second is channel.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ImportError
The audioread module is not installed.
*
Loading of the data failed.
"""
if not audio_modules['audioread']:
raise ImportError
data = np.array([])
rate = 0.0
with audioread.audio_open(filepath) as af:
rate = af.samplerate
data = np.zeros((int(np.ceil(af.samplerate*af.duration)), af.channels),
dtype="<i2")
index = 0
for buffer in af:
fulldata = np.frombuffer(buffer, dtype='<i2').reshape(-1, af.channels)
n = fulldata.shape[0]
if index + n > len(data):
n = len(fulldata) - index
if n <= 0:
break
data[index:index+n,:] = fulldata[:n,:]
index += n
return data/(2.0**15-1.0), float(rate)
audio_loader_funcs = (
('soundfile', load_soundfile),
('wave', load_wave),
('wavefile', load_wavefile),
('ewave', load_ewave),
('scipy.io.wavfile', load_wavfile),
('audioread', load_audioread),
)
"""List of implemented load functions.
Each element of the list is a tuple with the module's name and its
load function.
"""
def load_audio(filepath, verbose=0):
"""Call this function to load all channels of audio data from a file.
This function tries different python modules to load the audio file.
Parameters
----------
filepath: string
The full path and name of the file to load.
verbose: int
If larger than zero show detailed error/warning messages.
Returns
-------
data: array
All data traces as an 2-D numpy array, even for single channel data.
First dimension is time, second is channel.
Data values range maximally between -1 and 1.
rate: float
The sampling rate of the data in Hertz.
Raises
------
ValueError
Empty `filepath`.
FileNotFoundError
`filepath` is not an existing file.
EOFError
File size of `filepath` is zero.
IOError
Failed to load data.
Examples
--------
```
import matplotlib.pyplot as plt
from audioio import load_audio
data, rate = load_audio('some/audio.wav')
plt.plot(np.arange(len(data))/rate, data[:,0])
plt.show()
```
"""
# check values:
if filepath is None or len(filepath) == 0:
raise ValueError('input argument filepath is empty string!')
if not os.path.isfile(filepath):
raise FileNotFoundError(f'file "{filepath}" not found')
if os.path.getsize(filepath) <= 0:
raise EOFError(f'file "{filepath}" is empty (size=0)!')
# load an audio file by trying various modules:
not_installed = []
errors = [f'failed to load data from file "{filepath}":']
for lib, load_file in audio_loader_funcs:
if not audio_modules[lib]:
if verbose > 1:
print(f'unable to load data from file "{filepath}" using {lib} module: module not available')
not_installed.append(lib)
continue
try:
data, rate = load_file(filepath)
if len(data) > 0:
if verbose > 0:
print(f'loaded data from file "{filepath}" using {lib} module')
if verbose > 1:
print(f' sampling rate: {rate:g} Hz')
print(f' channels : {data.shape[1]}')
print(f' frames : {len(data)}')
return data, rate
except Exception as e:
errors.append(f' {lib} failed: {str(e)}')
if verbose > 1:
print(errors[-1])
if len(not_installed) > 0:
errors.append('\n You may need to install one of the ' + \
', '.join(not_installed) + ' packages.')
raise IOError('\n'.join(errors))
return np.zeros(0), 0.0
def metadata(filepath, store_empty=False):
""" Read metadata of an audio file.
Parameters
----------
filepath: string or file handle
The audio file from which to read metadata.
store_empty: bool
If `False` do not return meta data with empty values.
Returns
-------
meta_data: nested dict
Meta data contained in the audio file. Keys of the nested
dictionaries are always strings. If the corresponding
values are dictionaries, then the key is the section name
of the metadata contained in the dictionary. All other
types of values are values for the respective key. In
particular they are strings. But other
simple types like ints or floats are also allowed.
See `audioio.audiometadata` module for available functions
to work with such metadata.
Examples
--------
```
from audioio import metadata, print_metadata
md = metadata('data.wav')
print_metadata(md)
```
"""
try:
return metadata_riff(filepath, store_empty)
except ValueError: # not a RIFF file
return {}
def markers(filepath):
""" Read markers of an audio file.
See `audioio.audiomarkers` module for available functions
to work with markers.
Parameters
----------
filepath: string or file handle
The audio file.
Returns
-------
locs: 2-D array of ints
Marker positions (first column) and spans (second column)
for each marker (rows).
labels: 2-D array of string objects
Labels (first column) and texts (second column)
for each marker (rows).
Examples
--------
```
from audioio import markers, print_markers
locs, labels = markers('data.wav')
print_markers(locs, labels)
```
"""
try:
return markers_riff(filepath)
except ValueError: # not a RIFF file
return np.zeros((0, 2), dtype=int), np.zeros((0, 2), dtype=object)
def blocks(data, block_size, noverlap=0, start=0, stop=None):
"""Generator for blockwise processing of array data.
Parameters
----------
data: array
Data to loop over. First dimension is time.
block_size: int
Len of data blocks to be returned.
noverlap: int
Number of indices successive data points should overlap.
start: int
Optional first index from which on to return blocks of data.
stop: int
Optional last index until which to return blocks of data.
Yields
------
data: array
Successive slices of the input data.
Raises
------
ValueError
`noverlap` larger or equal to `block_size`.
Examples
--------
```
import numpy as np
from audioio import blocks
data = np.arange(20)
for x in blocks(data, 6, 2):
print(x)
```
results in
```text
[0 1 2 3 4 5]
[4 5 6 7 8 9]
[ 8 9 10 11 12 13]
[12 13 14 15 16 17]
[16 17 18 19]
```
Use it for processing long audio data, like computing a
spectrogram with overlap:
```
from scipy.signal import spectrogram
from audioio import AudioLoader, blocks
nfft = 2048
with AudioLoader('some/audio.wav') as data:
for x in blocks(data, 100*nfft, nfft//2):
f, t, Sxx = spectrogram(x, fs=data.samplerate,
nperseg=nfft, noverlap=nfft//2)
```
"""
if noverlap >= block_size:
raise ValueError(f'noverlap={noverlap} larger than block_size={block_size}')
if stop is None:
stop = len(data)
m = block_size - noverlap
n = (stop-start-noverlap)//m
if n == 0:
yield data[start:stop]
else:
for k in range(n):
yield data[start+k*m:start+k*m+block_size]
if stop - start - (k*m+block_size) > 0:
yield data[start+(k+1)*m:]
class BufferArray(object):
"""Random access to 2D data of which only a part is held in memory.
This is a base class for accessing large audio recordings either
from a file (class AudioLoader) or by computing its contents. The
BufferArray behaves like a single big ndarray with first dimension
indexing the frames and second dimension indexing the channels of
the audio data. Internally it only holds a part of the data in
memory.
Classes inheriting BufferArray just need to implement
```
self.load_buffer(offset, size, buffer)
```
This function needs to load the supplied 2-D `buffer` with `size`
frames of data starting at `offset`.
In the constructor or some kind of opening function, you need to
set the following member variables, followed by a call to
`_init_buffer()`:
```
self.samplerate # number of frames per second
self.channels # number of channels per frame
self.frames # total number of frames
self.shape = (self.frames, self.channels)
self.ndim # number of dimensions: always 2 (frames and channels)
self.size # total number of samples: frames times channels
self.buffersize # number of frames the buffer should hold
self.backsize # number of frames kept for moving back
self._init_buffer()
```
Parameters
----------
verbose: int
If larger than zero show detailed error/warning messages.
Attributes
----------
samplerate: float
The sampling rate of the data in seconds.
channels: int
The number of channels.
frames: int
The number of frames. Same as `len()`.
shape: tuple
Frames and channels of the data.
ndim: int
Number of dimensions: always 2 (frames and channels).
size: int
Total number of samples: frames times channels.
offset: int
Index of first frame in the current buffer.
buffer: array of floats
The curently available data.
ampl_min: float
Minimum amplitude the data supports.
ampl_max: float
Maximum amplitude the data supports.
Methods
-------
- `len()`: Number of frames.
- `__getitem__`: Access data.
- `update_buffer()`: Update the buffer for a range of frames.
- `load_buffer()`: Load a range of frames into a buffer.
Notes
-----
Access via `__getitem__` or `__next__` is slow!
Even worse, using numpy functions on this class first converts
it to a numpy array - that is something we actually do not want!
We should subclass directly from numpy.ndarray .
For details see http://docs.scipy.org/doc/numpy/user/basics.subclassing.html
When subclassing, there is an offset argument, that might help to
speed up `__getitem__` .
"""
def __init__(self, verbose=0):
self.samplerate = 0.0
self.channels = 0
self.frames = 0
self.shape = (0, 0)
self.ndim = 2
self.size = 0
self.ampl_min = -1.0
self.ampl_max = +1.0
self.offset = 0
self.buffersize = 0
self.backsize = 0
self.buffer = np.zeros((0, 0))
self.unwrap = False
self.unwrap_thresh = 0.0
self.unwrap_clips = False
self.unwrap_ampl = 1.0
self.unwrap_downscale = True
self.verbose = verbose
def __enter__(self):
return self
def __exit__(self, ex_type, ex_value, tb):
self.__del__()
return (ex_value is None)
def __len__(self):
return self.frames
def __iter__(self):
self.iter_counter = -1
return self
def __next__(self):
self.iter_counter += 1
if self.iter_counter >= self.frames:
raise StopIteration
else:
self.update_buffer(self.iter_counter, self.iter_counter + 1)
return self.buffer[self.iter_counter - self.offset,:]
def __getitem__(self, key):
"""Access data of the audio file."""
if type(key) is tuple:
index = key[0]
else:
index = key
if isinstance(index, slice):
start = index.start
stop = index.stop
step = index.step
if start is None:
start=0
else:
start = int(start)
if start < 0:
start += len(self)
if stop is None:
stop = len(self)
else:
stop = int(stop)
if stop < 0:
stop += len(self)
if stop > self.frames:
stop = self.frames
if step is None:
step = 1
else:
step = int(step)
self.update_buffer(start, stop)
newindex = slice(start-self.offset, stop-self.offset, step)
elif hasattr(index, '__len__'):
index = [inx if inx >= 0 else inx+len(self) for inx in index]
start = min(index)
stop = max(index)
self.update_buffer(start, stop+1)
newindex = [inx-self.offset for inx in index]
else:
if index > self.frames:
raise IndexError
index = int(index)
if index < 0:
index += len(self)
self.update_buffer(index, index+1)
newindex = index-self.offset
if type(key) is tuple:
newkey = (newindex,) + key[1:]
return self.buffer[newkey]
else:
return self.buffer[newindex]
def _init_buffer(self):
"""Allocate a buffer with zero frames but all the channels."""
self.buffer = np.empty((0, self.channels))
self.offset = 0
def update_buffer(self, start, stop):
"""Make sure that the buffer contains data between start and stop.
Parameters
----------
start: int
Index of the first frame for the buffer.
stop: int
Index of the last frame for the buffer.
"""
if start < self.offset or stop > self.offset + self.buffer.shape[0]:
offset, size = self._read_indices(start, stop)
r_offset, r_size = self._recycle_buffer(offset, size)
self.offset = offset
# load buffer content from file, this is backend specific:
data = self.buffer[r_offset-self.offset:
r_offset-self.offset+r_size,:]
self.load_buffer(r_offset, r_size, data)
if self.unwrap:
# TODO: handle edge effects!
unwrap(data, self.unwrap_thresh, self.unwrap_ampl)
if self.unwrap_clips:
data[data > self.ampl_max] = self.ampl_max
data[data < self.ampl_min] = self.ampl_min
elif self.unwrap_down_scale:
data *= 0.5
if self.verbose > 1:
print(f' loaded {self.buffer.shape[0]} frames from {self.offset} up to {self.offset+self.buffer.shape[0]}')
def _read_indices(self, start, stop):
"""Compute position and size for next read from file.
This takes buffersize and backsize into account.
Parameters
----------
start: int
Index of the first requested frame.
stop: int
Index of the last requested frame.
Returns
-------
offset: int
Frame index for the first frame in the buffer.
size: int
Number of frames the buffer should hold.
"""
offset = start
size = stop - start
if size < self.buffersize:
back = self.backsize
if self.buffersize - size < back:
back = self.buffersize - size
offset -= back
size = self.buffersize
if offset < 0:
offset = 0
if offset + size > self.frames:
offset = self.frames - size
if offset < 0:
offset = 0
size = self.frames - offset
if self.verbose > 2:
print(f' request {size:6d} frames at {offset}-{offset+size}')
return offset, size
def _recycle_buffer(self, offset, size):
"""Recycle buffer contents and return indices for data to be loaded from file.
Move already existing parts of the buffer to their new position (as
returned by _read_indices() ) and return position and size of
data chunk that still needs to be loaded from file.
Parameters
----------
offset: int
Frame index for the first frame in the buffer.
size: int
Number of frames the buffer should hold.
Returns
-------
r_offset: int
First frame to be read from file.
r_size: int
Number of frames to be read from file.
"""
def allocate_buffer(size):
"""Make sure the buffer has the right size."""
if size != self.buffer.shape[0]:
self.buffer = np.empty((size, self.channels))
r_offset = offset
r_size = size
if ( offset >= self.offset and
offset < self.offset + self.buffer.shape[0] ):
i = self.offset + self.buffer.shape[0] - offset
n = i
if n > size:
n = size
m = self.buffer.shape[0]
buffer = self.buffer[-i:m-i+n,:]
allocate_buffer(size)
self.buffer[:n,:] = buffer
r_offset += n
r_size -= n
if self.verbose > 2:
print(f' recycle {n:6d} frames from {self.offset+m-i}-{self.offset+m-i+n} of the old {m}-sized buffer to the front at {offset}-{offset+n} ({0}-{n} in buffer)')
elif ( offset + size > self.offset and
offset + size <= self.offset + self.buffer.shape[0] ):
n = offset + size - self.offset
m = self.buffer.shape[0]
buffer = self.buffer[:n,:]
allocate_buffer(size)
self.buffer[-n:,:] = buffer
r_size -= n
if self.verbose > 2:
print(f' recycle {n:6d} frames from {self.offset}-{self.offset+n} of the old {m}-sized buffer to the end at {offset+size-n}-{offset+size} ({size-n}-{size} in buffer)')
else:
allocate_buffer(size)
return r_offset, r_size
class AudioLoader(BufferArray):
"""Buffered reading of audio data for random access of the data in the file.
The class allows for reading very large audio files that do not
fit into memory.
An AudioLoader instance can be used like a huge read-only numpy array, i.e.
```
data = AudioLoader('path/to/audio/file.wav')
x = data[10000:20000,0]
```
The first index specifies the frame, the second one the channel.
Behind the scenes AudioLoader tries to open the audio file with
all available audio modules until it succeeds (first line). It
then reads data from the file as necessary for the requested data
(second line).
Reading sequentially through the file is always possible. Some
modules, however, (e.g. audioread, needed for mp3 files) can only
read forward. If previous data are requested, then the file is read
from the beginning. This slows down access to previous data
considerably. Use the `backsize` argument of the open function to
make sure some data are loaded into the buffer before the requested
frame. Then a subsequent access to the data within backsize `seconds`
before that frame can still be handled without the need to reread
the file from the beginning.
Usage
-----
With context management:
```
import audioio as aio
with aio.AudioLoader(filepath, 60.0, 10.0) as data:
# do something with the content of the file:
x = data[0:10000]
y = data[10000:20000]
z = x + y
```
For using a specific audio module, here the audioread module:
```
data = aio.AudioLoader()
with data.open_audioread(filepath, 60.0, 10.0):
# do something ...
```
Use `blocks()` for sequential, blockwise reading and processing:
```
from scipy.signal import spectrogram
nfft = 2048
with aio.AudioLoader('some/audio.wav') as data:
for x in data.blocks(100*nfft, nfft//2):
f, t, Sxx = spectrogram(x, fs=data.samplerate,
nperseg=nfft, noverlap=nfft//2)
```
For loop iterates over single frames (1-D arrays containing samples for each channel):
```
with aio.AudioLoader('some/audio.wav') as data:
for x in data:
print(x)
```
Traditional open and close:
```
data = aio.AudioLoader(filepath, 60.0)
x = data[:,:] # read the whole file
data.close()
```
this is the same as:
```
data = aio.AudioLoader()
data.open(filepath, 60.0)
...
```
Parameters
----------
filepath: string
Name of the file.
buffersize: float
Size of internal buffer in seconds.
backsize: float
Part of the buffer to be loaded before the requested start index in seconds.
verbose: int
If larger than zero show detailed error/warning messages.
store_empty: bool
If `False` do not return meta data with empty values.
Attributes
----------
filepath: str
Path and name of the file.
samplerate: float
The sampling rate of the data in seconds.
channels: int
The number of channels.
frames: int
The number of frames in the file. Same as `len()`.
format: str or None
Format of the audio file.
encoding: str or None
Encoding/subtype of the audio file.
shape: tuple
Frames and channels of the data.
offset: int
Index of first frame in the current buffer.
buffer: array of floats
The curently available data from the file.
ampl_min: float
Minimum amplitude the file format supports.
Always -1.0 for audio data.
ampl_max: float
Maximum amplitude the file format supports.
Always +1.0 for audio data.
Methods
-------
- `len()`: Number of frames.
- `open()`: Open an audio file by trying available audio modules.
- `open_*()`: Open an audio file with the respective audio module.
- `__getitem__`: Access data of the audio file.
- `update_buffer()`: Update the internal buffer for a range of frames.
- `load_buffer()`: Load a range of frames into a buffer.
- `blocks()`: Generator for blockwise processing of AudioLoader data.
- `format_dict()`: technical infos about how the data are stored.
- `metadata()`: Metadata stored along with the audio data.
- `markers()`: Markers stored along with the audio data.
- `set_unwrap()`: Set parameters for unwrapping clipped data.
- `close()`: Close the file.
Notes
-----
Access via `__getitem__` or `__next__` is slow!
Even worse, using numpy functions on this class first converts
it to a numpy array - that is something we actually do not want!
We should subclass directly from numpy.ndarray .
For details see http://docs.scipy.org/doc/numpy/user/basics.subclassing.html
When subclassing, there is an offset argument, that might help to
speed up `__getitem__` .
"""
def __init__(self, filepath=None, buffersize=10.0, backsize=0.0,
verbose=0, **meta_kwargs):
super().__init__(verbose)
self.format = None
self.encoding = None
self._metadata = None
self._locs = None
self._labels = None
self._load_metadata = metadata
self._load_markers = markers
self._metadata_kwargs = meta_kwargs
self.filepath = None
self.sf = None
self.close = self._close
if filepath is not None:
self.open(filepath, buffersize, backsize, verbose)
numpy_encodings = {np.dtype(np.int64): 'PCM_64',
np.dtype(np.int32): 'PCM_32',
np.dtype(np.int16): 'PCM_16',
np.dtype(np.single): 'FLOAT',
np.dtype(np.double): 'DOUBLE'}
""" Map numpy dtypes to encodings.
"""
def _close(self):
pass
def __del__(self):
self.close()
def blocks(self, block_size, noverlap=0, start=0, stop=None):
"""Generator for blockwise processing of AudioLoader data.
Parameters