-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathminiaudio.py
1733 lines (1529 loc) · 80.2 KB
/
miniaudio.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
"""
Python interface to the miniaudio library (https://github.com/dr-soft/miniaudio)
Author: Irmen de Jong (irmen@razorvine.net)
Software license: "MIT software license". See http://opensource.org/licenses/MIT
"""
__version__ = "1.62.dev0"
import abc
import sys
import os
import io
import array
import urllib.request
import inspect
import time
import html
import threading
from enum import Enum
from typing import Generator, List, Dict, Set, Optional, Union, Any, Callable
from _miniaudio import ffi, lib
try:
import numpy
except ImportError:
numpy = None # type: ignore
lib.init_miniaudio()
class FileFormat(Enum):
"""Audio file format"""
UNKNOWN = lib.ma_encoding_format_unknown
WAV = lib.ma_encoding_format_wav
FLAC = lib.ma_encoding_format_flac
MP3 = lib.ma_encoding_format_mp3
VORBIS = lib.ma_encoding_format_vorbis
class SampleFormat(Enum):
"""Sample format in memory"""
UNKNOWN = lib.ma_format_unknown
UNSIGNED8 = lib.ma_format_u8
SIGNED16 = lib.ma_format_s16
SIGNED24 = lib.ma_format_s24
SIGNED32 = lib.ma_format_s32
FLOAT32 = lib.ma_format_f32
class DeviceType(Enum):
"""Type of audio device"""
PLAYBACK = lib.ma_device_type_playback
CAPTURE = lib.ma_device_type_capture
DUPLEX = lib.ma_device_type_duplex
class DitherMode(Enum):
"""How to dither when converting"""
NONE = lib.ma_dither_mode_none
RECTANGLE = lib.ma_dither_mode_rectangle
TRIANGLE = lib.ma_dither_mode_triangle
class ChannelMixMode(Enum):
"""How to mix channels when converting"""
RECTANGULAR = lib.ma_channel_mix_mode_rectangular
SIMPLE = lib.ma_channel_mix_mode_simple
CUSTOMWEIGHTS = lib.ma_channel_mix_mode_custom_weights
DEFAULT = lib.ma_channel_mix_mode_default
class Backend(Enum):
"""Operating system audio backend to use (only a subset will be available)"""
WASAPI = lib.ma_backend_wasapi
DSOUND = lib.ma_backend_dsound
WINMM = lib.ma_backend_winmm
COREAUDIO = lib.ma_backend_coreaudio
SNDIO = lib.ma_backend_sndio
AUDIO4 = lib.ma_backend_audio4
OSS = lib.ma_backend_oss
PULSEAUDIO = lib.ma_backend_pulseaudio
ALSA = lib.ma_backend_alsa
JACK = lib.ma_backend_jack
AAUDIO = lib.ma_backend_aaudio
OPENSL = lib.ma_backend_opensl
WEBAUDIO = lib.ma_backend_webaudio
CUSTOM = lib.ma_backend_custom
NULL = lib.ma_backend_null
class ThreadPriority(Enum):
"""The priority of the worker thread (default=HIGHEST)"""
IDLE = lib.ma_thread_priority_idle
LOWEST = lib.ma_thread_priority_lowest
LOW = lib.ma_thread_priority_low
NORMAL = lib.ma_thread_priority_normal
HIGH = lib.ma_thread_priority_high
HIGHEST = lib.ma_thread_priority_highest
REALTIME = lib.ma_thread_priority_realtime
DEFAULT = lib.ma_thread_priority_default
class SeekOrigin(Enum):
"""How to seek() in a source"""
START = lib.ma_seek_origin_start
CURRENT = lib.ma_seek_origin_current
FramesType = Union[bytes, array.array]
PlaybackCallbackGeneratorType = Generator[FramesType, int, None]
CaptureCallbackGeneratorType = Generator[None, FramesType, None]
DuplexCallbackGeneratorType = Generator[FramesType, FramesType, None]
GeneratorTypes = Union[PlaybackCallbackGeneratorType, CaptureCallbackGeneratorType, DuplexCallbackGeneratorType]
class SoundFileInfo:
"""Contains various properties of an audio file."""
def __init__(self, name: str, file_format: FileFormat, nchannels: int, sample_rate: int,
sample_format: SampleFormat, duration: float, num_frames: int,
sub_format: int = None) -> None:
self.name = name
self.nchannels = nchannels
self.sample_rate = sample_rate
self.sample_format = sample_format
self.sample_format_name = ffi.string(lib.ma_get_format_name(sample_format.value)).decode()
self.sample_width = width_from_format(sample_format)
self.num_frames = num_frames
self.duration = duration
self.file_format = file_format
self.sub_format = sub_format
def __str__(self) -> str:
fileformatdisplay = self.file_format.name
if self.sub_format:
fileformatdisplay += " (fmt=" + str(self.sub_format) + ")"
return "<{clazz}: '{name}' {fileformatdisplay} {nchannels} ch, {sample_rate} hz, {sample_format.name}, " \
"{num_frames} frames={duration:.2f} sec.>".format(clazz=self.__class__.__name__,
fileformatdisplay=fileformatdisplay, **(vars(self)))
def __repr__(self) -> str:
return str(self)
class DecodedSoundFile(SoundFileInfo):
"""Contains various properties and also the PCM frames of a fully decoded audio file."""
def __init__(self, name: str, nchannels: int, sample_rate: int,
sample_format: SampleFormat, samples: array.array) -> None:
num_frames = len(samples) // nchannels
duration = num_frames / sample_rate
super().__init__(name, FileFormat.UNKNOWN, nchannels, sample_rate, sample_format, duration, num_frames)
self.samples = samples
class MiniaudioError(Exception):
"""When a miniaudio specific error occurs."""
pass
class DecodeError(MiniaudioError):
"""When something went wrong during decoding an audio file."""
pass
def get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file."""
ext = os.path.splitext(filename)[1].lower()
if ext in (".ogg", ".vorbis"):
return vorbis_get_file_info(filename)
elif ext == ".mp3":
return mp3_get_file_info(filename)
elif ext == ".flac":
return flac_get_file_info(filename)
elif ext == ".wav":
return wav_get_file_info(filename)
raise DecodeError("unsupported file format")
def read_file(filename: str, convert_to_16bit: bool = False) -> DecodedSoundFile:
"""Reads and decodes the whole audio file.
Miniaudio will attempt to return the sound data in exactly the same format as in the file.
Unless you set convert_convert_to_16bit to True, then the result is always a 16 bit sample format.
"""
ext = os.path.splitext(filename)[1].lower()
if ext in (".ogg", ".vorbis"):
if convert_to_16bit:
return vorbis_read_file(filename)
else:
vorbis = vorbis_get_file_info(filename)
if vorbis.sample_format == SampleFormat.SIGNED16:
return vorbis_read_file(filename)
else:
raise MiniaudioError("file has sample format that must be converted")
elif ext == ".mp3":
if convert_to_16bit:
return mp3_read_file_s16(filename)
else:
mp3 = mp3_get_file_info(filename)
if mp3.sample_format == SampleFormat.SIGNED16:
return mp3_read_file_s16(filename)
elif mp3.sample_format == SampleFormat.FLOAT32:
return mp3_read_file_f32(filename)
else:
raise MiniaudioError("file has sample format that must be converted")
elif ext == ".flac":
if convert_to_16bit:
return flac_read_file_s16(filename)
else:
flac = flac_get_file_info(filename)
if flac.sample_format == SampleFormat.SIGNED16:
return flac_read_file_s16(filename)
elif flac.sample_format == SampleFormat.SIGNED32:
return flac_read_file_s32(filename)
elif flac.sample_format == SampleFormat.FLOAT32:
return flac_read_file_f32(filename)
else:
raise MiniaudioError("file has sample format that must be converted")
elif ext == ".wav":
if convert_to_16bit:
return wav_read_file_s16(filename)
else:
wav = wav_get_file_info(filename)
if wav.sample_format == SampleFormat.SIGNED16:
return wav_read_file_s16(filename)
elif wav.sample_format == SampleFormat.SIGNED32:
return wav_read_file_s32(filename)
elif wav.sample_format == SampleFormat.FLOAT32:
return wav_read_file_f32(filename)
else:
raise MiniaudioError("file has sample format that must be converted")
raise DecodeError("unsupported file format")
def vorbis_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (vorbis format)."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("int *") as error:
vorbis = lib.stb_vorbis_open_filename(filenamebytes, error, ffi.NULL)
if not vorbis:
raise DecodeError("could not open/decode file")
try:
info = lib.stb_vorbis_get_info(vorbis)
duration = lib.stb_vorbis_stream_length_in_seconds(vorbis)
num_frames = lib.stb_vorbis_stream_length_in_samples(vorbis)
return SoundFileInfo(filename, FileFormat.VORBIS, info.channels, info.sample_rate,
SampleFormat.SIGNED16, duration, num_frames)
finally:
lib.stb_vorbis_close(vorbis)
def vorbis_get_info(data: bytes) -> SoundFileInfo:
"""Fetch some information about the audio data (vorbis format)."""
with ffi.new("int *") as error:
vorbis = lib.stb_vorbis_open_memory(data, len(data), error, ffi.NULL)
if not vorbis:
raise DecodeError("could not open/decode data")
try:
info = lib.stb_vorbis_get_info(vorbis)
duration = lib.stb_vorbis_stream_length_in_seconds(vorbis)
num_frames = lib.stb_vorbis_stream_length_in_samples(vorbis)
return SoundFileInfo("<memory>", FileFormat.VORBIS, info.channels, info.sample_rate,
SampleFormat.SIGNED16, duration, num_frames)
finally:
lib.stb_vorbis_close(vorbis)
def vorbis_read_file(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole vorbis audio file. Resulting sample format is 16 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("int *") as channels, ffi.new("int *") as sample_rate, ffi.new("short **") as output:
num_frames = lib.stb_vorbis_decode_filename(filenamebytes, channels, sample_rate, output)
if num_frames <= 0:
raise DecodeError("cannot load/decode file")
try:
buffer = ffi.buffer(output[0], num_frames * channels[0] * 2)
samples = _create_int_array(2)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.free(output[0])
def vorbis_read(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole vorbis audio data. Resulting sample format is 16 bits signed integer."""
with ffi.new("int *") as channels, ffi.new("int *") as sample_rate, ffi.new("short **") as output:
num_samples = lib.stb_vorbis_decode_memory(data, len(data), channels, sample_rate, output)
if num_samples <= 0:
raise DecodeError("cannot load/decode data")
try:
buffer = ffi.buffer(output[0], num_samples * channels[0] * 2)
samples = _create_int_array(2)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.free(output[0])
def vorbis_stream_file(filename: str, seek_frame: int = 0) -> Generator[array.array, None, None]:
"""Streams the ogg vorbis audio file as interleaved 16 bit signed integer sample arrays segments.
This uses a variable unconfigurable chunk size and cannot be used as a generic miniaudio decoder input stream.
Consider using stream_file() instead."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("int *") as error:
vorbis = lib.stb_vorbis_open_filename(filenamebytes, error, ffi.NULL)
if not vorbis:
raise DecodeError("could not open/decode file")
try:
info = lib.stb_vorbis_get_info(vorbis)
with ffi.new("short[]", 4096 * info.channels) as decode_buffer1, \
ffi.new("short[]", 4096 * info.channels) as decode_buffer2:
decodebuf_ptr1 = ffi.cast("short *", decode_buffer1)
decodebuf_ptr2 = ffi.cast("short *", decode_buffer2)
if seek_frame > 0:
result = lib.stb_vorbis_seek_frame(vorbis, seek_frame)
if result <= 0:
raise DecodeError("can't seek")
# note: we decode several frames to reduce the overhead of very small sample sizes a little
while True:
num_samples1 = lib.stb_vorbis_get_frame_short_interleaved(vorbis, info.channels, decodebuf_ptr1,
4096 * info.channels)
num_samples2 = lib.stb_vorbis_get_frame_short_interleaved(vorbis, info.channels, decodebuf_ptr2,
4096 * info.channels)
if num_samples1 + num_samples2 <= 0:
break
buffer = ffi.buffer(decode_buffer1, num_samples1 * 2 * info.channels)
samples = _create_int_array(2)
samples.frombytes(buffer)
if num_samples2 > 0:
buffer = ffi.buffer(decode_buffer2, num_samples2 * 2 * info.channels)
samples.frombytes(buffer)
yield samples
finally:
lib.stb_vorbis_close(vorbis)
def flac_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (flac format)."""
filenamebytes = _get_filename_bytes(filename)
flac = lib.drflac_open_file(filenamebytes, ffi.NULL)
if not flac:
raise DecodeError("could not open/decode file")
try:
duration = flac.totalPCMFrameCount / flac.sampleRate
sample_width = flac.bitsPerSample // 8
return SoundFileInfo(filename, FileFormat.FLAC, flac.channels, flac.sampleRate,
_format_from_width(sample_width), duration, flac.totalPCMFrameCount)
finally:
lib.drflac_close(flac)
def flac_get_info(data: bytes) -> SoundFileInfo:
"""Fetch some information about the audio data (flac format)."""
flac = lib.drflac_open_memory(data, len(data), ffi.NULL)
if not flac:
raise DecodeError("could not open/decode data")
try:
duration = flac.totalPCMFrameCount / flac.sampleRate
sample_width = flac.bitsPerSample // 8
return SoundFileInfo("<memory>", FileFormat.FLAC, flac.channels, flac.sampleRate,
_format_from_width(sample_width), duration, flac.totalPCMFrameCount)
finally:
lib.drflac_close(flac)
def flac_read_file_s32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 32 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_file_and_read_pcm_frames_s32(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = _create_int_array(4)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.SIGNED32, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_read_file_s16(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 16 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_file_and_read_pcm_frames_s16(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 2)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_read_file_f32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_file_and_read_pcm_frames_f32(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.FLOAT32, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_read_s32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio data. Resulting sample format is 32 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_memory_and_read_pcm_frames_s32(data, len(data),
channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = _create_int_array(4)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.SIGNED32, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_read_s16(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio data. Resulting sample format is 16 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_memory_and_read_pcm_frames_s16(data, len(data),
channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 2)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_read_f32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole flac audio file. Resulting sample format is 32 bits float."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drflac_uint64 *") as num_frames:
memory = lib.drflac_open_memory_and_read_pcm_frames_f32(data, len(data),
channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.FLOAT32, samples)
finally:
lib.drflac_free(memory, ffi.NULL)
def flac_stream_file(filename: str, frames_to_read: int = 1024,
seek_frame: int = 0) -> Generator[array.array, None, None]:
"""Streams the flac audio file as interleaved 16 bit signed integer sample arrays segments.
This uses a fixed chunk size and cannot be used as a generic miniaudio decoder input stream.
Consider using stream_file() instead."""
filenamebytes = _get_filename_bytes(filename)
flac = lib.drflac_open_file(filenamebytes, ffi.NULL)
if not flac:
raise DecodeError("could not open/decode file")
if seek_frame > 0:
result = lib.drflac_seek_to_pcm_frame(flac, seek_frame)
if result <= 0:
raise DecodeError("can't seek")
try:
with ffi.new("drflac_int16[]", frames_to_read * flac.channels) as decodebuffer:
buf_ptr = ffi.cast("drflac_int16 *", decodebuffer)
while True:
num_samples = lib.drflac_read_pcm_frames_s16(flac, frames_to_read, buf_ptr)
if num_samples <= 0:
break
buffer = ffi.buffer(decodebuffer, num_samples * 2 * flac.channels)
samples = _create_int_array(2)
samples.frombytes(buffer)
yield samples
finally:
lib.drflac_close(flac)
def mp3_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (mp3 format)."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3 *") as mp3:
if not lib.drmp3_init_file(mp3, filenamebytes, ffi.NULL):
raise DecodeError("could not open/decode file")
try:
num_frames = lib.drmp3_get_pcm_frame_count(mp3)
duration = num_frames / mp3.sampleRate
return SoundFileInfo(filename, FileFormat.MP3, mp3.channels, mp3.sampleRate,
SampleFormat.SIGNED16, duration, num_frames)
finally:
lib.drmp3_uninit(mp3)
def mp3_get_info(data: bytes) -> SoundFileInfo:
"""Fetch some information about the audio data (mp3 format)."""
with ffi.new("drmp3 *") as mp3:
if not lib.drmp3_init_memory(mp3, data, len(data), ffi.NULL):
raise DecodeError("could not open/decode data")
try:
num_frames = lib.drmp3_get_pcm_frame_count(mp3)
duration = num_frames / mp3.sampleRate
return SoundFileInfo("<memory>", FileFormat.MP3, mp3.channels, mp3.sampleRate,
SampleFormat.SIGNED16, duration, num_frames)
finally:
lib.drmp3_uninit(mp3)
def mp3_read_file_f32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole mp3 audio file. Resulting sample format is 32 bits float."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3_config *") as config, ffi.new("drmp3_uint64 *") as num_frames:
memory = lib.drmp3_open_file_and_read_pcm_frames_f32(filenamebytes, config, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * config.channels * 4)
samples.frombytes(buffer)
return DecodedSoundFile(filename, config.channels, config.sampleRate, SampleFormat.FLOAT32, samples)
finally:
lib.drmp3_free(memory, ffi.NULL)
def mp3_read_file_s16(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole mp3 audio file. Resulting sample format is 16 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3_config *") as config, ffi.new("drmp3_uint64 *") as num_frames:
memory = lib.drmp3_open_file_and_read_pcm_frames_s16(filenamebytes, config, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * config.channels * 2)
samples.frombytes(buffer)
return DecodedSoundFile(filename, config.channels, config.sampleRate, SampleFormat.SIGNED16, samples)
finally:
lib.drmp3_free(memory, ffi.NULL)
def mp3_read_f32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole mp3 audio data. Resulting sample format is 32 bits float."""
with ffi.new("drmp3_config *") as config, ffi.new("drmp3_uint64 *") as num_frames:
memory = lib.drmp3_open_memory_and_read_pcm_frames_f32(data, len(data), config, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * config.channels * 4)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", config.channels, config.sampleRate, SampleFormat.FLOAT32, samples)
finally:
lib.drmp3_free(memory, ffi.NULL)
def mp3_read_s16(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole mp3 audio data. Resulting sample format is 16 bits signed integer."""
with ffi.new("drmp3_config *") as config, ffi.new("drmp3_uint64 *") as num_frames:
memory = lib.drmp3_open_memory_and_read_pcm_frames_s16(data, len(data), config, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * config.channels * 2)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", config.channels, config.sampleRate, SampleFormat.SIGNED16, samples)
finally:
lib.drmp3_free(memory, ffi.NULL)
def mp3_stream_file(filename: str, frames_to_read: int = 1024, seek_frame: int = 0) -> Generator[array.array, None, None]:
"""Streams the mp3 audio file as interleaved 16 bit signed integer sample arrays segments.
This uses a fixed chunk size and cannot be used as a generic miniaudio decoder input stream.
Consider using stream_file() instead."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drmp3 *") as mp3:
if not lib.drmp3_init_file(mp3, filenamebytes, ffi.NULL):
raise DecodeError("could not open/decode file")
if seek_frame > 0:
result = lib.drmp3_seek_to_pcm_frame(mp3, seek_frame)
if result <= 0:
raise DecodeError("can't seek")
try:
with ffi.new("drmp3_int16[]", frames_to_read * mp3.channels) as decodebuffer:
buf_ptr = ffi.cast("drmp3_int16 *", decodebuffer)
while True:
num_samples = lib.drmp3_read_pcm_frames_s16(mp3, frames_to_read, buf_ptr)
if num_samples <= 0:
break
buffer = ffi.buffer(decodebuffer, num_samples * 2 * mp3.channels)
samples = _create_int_array(2)
samples.frombytes(buffer)
yield samples
finally:
lib.drmp3_uninit(mp3)
def wav_get_file_info(filename: str) -> SoundFileInfo:
"""Fetch some information about the audio file (wav format)."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drwav*") as wav:
if not lib.drwav_init_file(wav, filenamebytes, ffi.NULL):
raise DecodeError("could not open/decode file")
try:
duration = wav.totalPCMFrameCount / wav.sampleRate
sample_width = wav.bitsPerSample // 8
is_float = wav.translatedFormatTag == lib.DR_WAVE_FORMAT_IEEE_FLOAT
subformat = wav.translatedFormatTag
return SoundFileInfo(filename, FileFormat.WAV, wav.channels, wav.sampleRate,
_format_from_width(sample_width, is_float), duration, wav.totalPCMFrameCount,
sub_format=subformat)
finally:
lib.drwav_uninit(wav)
def wav_get_info(data: bytes) -> SoundFileInfo:
"""Fetch some information about the audio data (wav format)."""
with ffi.new("drwav*") as wav:
if not lib.drwav_init_memory(wav, data, len(data), ffi.NULL):
raise DecodeError("could not open/decode data")
try:
duration = wav.totalPCMFrameCount / wav.sampleRate
sample_width = wav.bitsPerSample // 8
is_float = wav.translatedFormatTag == lib.DR_WAVE_FORMAT_IEEE_FLOAT
return SoundFileInfo("<memory>", FileFormat.WAV, wav.channels, wav.sampleRate,
_format_from_width(sample_width, is_float), duration, wav.totalPCMFrameCount)
finally:
lib.drwav_uninit(wav)
def wav_read_file_s32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio file. Resulting sample format is 32 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_file_and_read_pcm_frames_s32(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = _create_int_array(4)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.SIGNED32, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_read_file_s16(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio file. Resulting sample format is 16 bits signed integer."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_file_and_read_pcm_frames_s16(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 2)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_read_file_f32(filename: str) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio file. Resulting sample format is 32 bits float."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_file_and_read_pcm_frames_f32(filenamebytes, channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode file")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile(filename, channels[0], sample_rate[0], SampleFormat.FLOAT32, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_read_s32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio data. Resulting sample format is 32 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_memory_and_read_pcm_frames_s32(data, len(data), channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = _create_int_array(4)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.SIGNED32, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_read_s16(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio data. Resulting sample format is 16 bits signed integer."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_memory_and_read_pcm_frames_s16(data, len(data), channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = _create_int_array(2)
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 2)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.SIGNED16, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_read_f32(data: bytes) -> DecodedSoundFile:
"""Reads and decodes the whole wav audio data. Resulting sample format is 32 bits float."""
with ffi.new("unsigned int *") as channels, \
ffi.new("unsigned int *") as sample_rate, \
ffi.new("drwav_uint64 *") as num_frames:
memory = lib.drwav_open_memory_and_read_pcm_frames_f32(data, len(data), channels, sample_rate, num_frames, ffi.NULL)
if not memory:
raise DecodeError("cannot load/decode data")
try:
samples = array.array('f')
buffer = ffi.buffer(memory, num_frames[0] * channels[0] * 4)
samples.frombytes(buffer)
return DecodedSoundFile("<memory>", channels[0], sample_rate[0], SampleFormat.FLOAT32, samples)
finally:
lib.drwav_free(memory, ffi.NULL)
def wav_stream_file(filename: str, frames_to_read: int = 1024,
seek_frame: int = 0) -> Generator[array.array, None, None]:
"""Streams the WAV audio file as interleaved 16 bit signed integer sample arrays segments.
This uses a fixed chunk size and cannot be used as a generic miniaudio decoder input stream.
Consider using stream_file() instead."""
filenamebytes = _get_filename_bytes(filename)
with ffi.new("drwav*") as wav:
if not lib.drwav_init_file(wav, filenamebytes, ffi.NULL):
raise DecodeError("could not open/decode file")
if seek_frame > 0:
result = lib.drwav_seek_to_pcm_frame(wav, seek_frame)
if result <= 0:
raise DecodeError("can't seek")
try:
with ffi.new("drwav_int16[]", frames_to_read * wav.channels) as decodebuffer:
buf_ptr = ffi.cast("drwav_int16 *", decodebuffer)
while True:
num_samples = lib.drwav_read_pcm_frames_s16(wav, frames_to_read, buf_ptr)
if num_samples <= 0:
break
buffer = ffi.buffer(decodebuffer, num_samples * 2 * wav.channels)
samples = _create_int_array(2)
samples.frombytes(buffer)
yield samples
finally:
lib.drwav_uninit(wav)
def wav_write_file(filename: str, sound: DecodedSoundFile) -> None:
"""Writes the pcm sound to a WAV file"""
with ffi.new("drwav_data_format*") as fmt, ffi.new("drwav*") as pwav:
fmt.container = lib.drwav_container_riff
fmt.format = sound.sub_format or lib.DR_WAVE_FORMAT_PCM
fmt.channels = sound.nchannels
fmt.sampleRate = sound.sample_rate
fmt.bitsPerSample = sound.sample_width * 8
# what about floating point format?
filename_bytes = filename.encode(sys.getfilesystemencoding())
if not lib.drwav_init_file_write_sequential(pwav, filename_bytes,
fmt, sound.num_frames * sound.nchannels, ffi.NULL):
raise IOError("can't open file for writing")
try:
lib.drwav_write_pcm_frames(pwav, sound.num_frames, sound.samples.tobytes())
finally:
lib.drwav_uninit(pwav)
def _create_int_array(itemsize: int) -> array.array:
for typecode in "Bhilq":
a = array.array(typecode)
if a.itemsize == itemsize:
return a
raise ValueError("cannot create array")
def _get_filename_bytes(filename: str) -> bytes:
filename2 = os.path.expanduser(filename)
if not os.path.isfile(filename2):
raise FileNotFoundError(filename)
return filename2.encode(sys.getfilesystemencoding())
class Devices:
"""Query the audio playback and record devices that miniaudio provides"""
def __init__(self, backends: Optional[List[Backend]] = None) -> None:
self._context = ffi.NULL
context = ffi.new("ma_context*")
if backends:
backends_mem = ffi.new("ma_backend[]", len(backends))
for i, b in enumerate(backends):
backends_mem[i] = b.value
result = lib.ma_context_init(backends_mem, len(backends), ffi.NULL, context)
else:
result = lib.ma_context_init(ffi.NULL, 0, ffi.NULL, context)
if result != lib.MA_SUCCESS:
raise MiniaudioError("cannot init context", result)
self._context = context
self.backend = ffi.string(lib.ma_get_backend_name(self._context[0].backend)).decode()
def get_playbacks(self) -> List[Dict[str, Any]]:
"""Get a list of playback devices and some details about them"""
with ffi.new("ma_device_info**") as playback_infos, ffi.new("ma_uint32*") as playback_count:
result = lib.ma_context_get_devices(self._context, playback_infos, playback_count, ffi.NULL, ffi.NULL)
if result != lib.MA_SUCCESS:
raise MiniaudioError("cannot get device infos", result)
devs = []
for i in range(playback_count[0]):
ma_device_info = playback_infos[0][i]
dev_id = ffi.new("ma_device_id *", ma_device_info.id) # copy the id memory
info = {
"name": ffi.string(ma_device_info.name).decode(),
"type": DeviceType.PLAYBACK,
"id": dev_id
}
info.update(self._get_info(DeviceType.PLAYBACK, ma_device_info))
devs.append(info)
return devs
def get_captures(self) -> List[Dict[str, Any]]:
"""Get a list of capture devices and some details about them"""
with ffi.new("ma_device_info**") as capture_infos, ffi.new("ma_uint32*") as capture_count:
result = lib.ma_context_get_devices(self._context, ffi.NULL, ffi.NULL, capture_infos, capture_count)
if result != lib.MA_SUCCESS:
raise MiniaudioError("cannot get device infos", result)
devs = []
for i in range(capture_count[0]):
ma_device_info = capture_infos[0][i]
dev_id = ffi.new("ma_device_id *", ma_device_info.id) # copy the id memory
info = {
"name": ffi.string(ma_device_info.name).decode(),
"type": DeviceType.CAPTURE,
"id": dev_id
}
info.update(self._get_info(DeviceType.CAPTURE, ma_device_info))
devs.append(info)
return devs
def _get_info(self, device_type: DeviceType, device_info: ffi.CData) -> Dict[str, Any]:
# obtain detailed info about the device
result = lib.ma_context_get_device_info(self._context, device_type.value, ffi.addressof(device_info.id), ffi.addressof(device_info))
if result != lib.MA_SUCCESS:
raise MiniaudioError("can't get device info")
formats = []
for fmt in range(device_info.nativeDataFormatCount):
data_format = device_info.nativeDataFormats[fmt]
formats.append({
"format": ffi.string(lib.ma_get_format_name(data_format.format)).decode(),
"samplerate": data_format.sampleRate,
"channels": data_format.channels
})
return {"formats": formats}
def __del__(self):
lib.ma_context_uninit(self._context)
def width_from_format(sampleformat: SampleFormat) -> int:
"""returns the sample width in bytes, of the given sample format."""
widths = {
SampleFormat.UNKNOWN: 0,
SampleFormat.UNSIGNED8: 1,
SampleFormat.SIGNED16: 2,
SampleFormat.SIGNED24: 3,
SampleFormat.SIGNED32: 4,
SampleFormat.FLOAT32: 4
}
if sampleformat in widths:
return widths[sampleformat]
raise MiniaudioError("unsupported sample format", sampleformat)
def _array_proto_from_format(sampleformat: SampleFormat) -> array.array:
arrays = {
SampleFormat.UNSIGNED8: _create_int_array(1),
SampleFormat.SIGNED16: _create_int_array(2),
SampleFormat.SIGNED32: _create_int_array(4),
SampleFormat.FLOAT32: array.array('f')
}
if sampleformat in arrays:
return arrays[sampleformat]
raise MiniaudioError("the requested sample format can not be used directly: "
+ sampleformat.name + " (convert it first)")
def _format_from_width(sample_width: int, is_float: bool = False) -> SampleFormat:
if is_float:
return SampleFormat.FLOAT32
elif sample_width == 1:
return SampleFormat.UNSIGNED8
elif sample_width == 2:
return SampleFormat.SIGNED16
elif sample_width == 3:
return SampleFormat.SIGNED24
elif sample_width == 4:
return SampleFormat.SIGNED32
elif sample_width == 0:
return SampleFormat.UNKNOWN
else:
raise MiniaudioError("unsupported sample width", sample_width)
def decode_file(filename: str, output_format: SampleFormat = SampleFormat.SIGNED16,
nchannels: int = 2, sample_rate: int = 44100, dither: DitherMode = DitherMode.NONE) -> DecodedSoundFile:
"""Convenience function to decode any supported audio file to raw PCM samples in your chosen format."""
sample_width = width_from_format(output_format)
samples = _array_proto_from_format(output_format)
filenamebytes = _get_filename_bytes(filename)
with ffi.new("ma_uint64 *") as frames, ffi.new("void **") as memory:
decoder_config = lib.ma_decoder_config_init(output_format.value, nchannels, sample_rate)
decoder_config.ditherMode = dither.value
result = lib.ma_decode_file(filenamebytes, ffi.addressof(decoder_config), frames, memory)
if result != lib.MA_SUCCESS:
raise DecodeError("failed to decode file", result)
buffer = ffi.buffer(memory[0], frames[0] * nchannels * sample_width)
samples.frombytes(buffer)
lib.ma_free(memory[0], ffi.NULL)
return DecodedSoundFile(filename, nchannels, sample_rate, output_format, samples)
def decode(data: bytes, output_format: SampleFormat = SampleFormat.SIGNED16,
nchannels: int = 2, sample_rate: int = 44100, dither: DitherMode = DitherMode.NONE) -> DecodedSoundFile:
"""Convenience function to decode any supported audio file in memory to raw PCM samples in your chosen format."""
sample_width = width_from_format(output_format)
samples = _array_proto_from_format(output_format)
with ffi.new("ma_uint64 *") as frames, ffi.new("void **") as memory:
decoder_config = lib.ma_decoder_config_init(output_format.value, nchannels, sample_rate)
decoder_config.ditherMode = dither.value
result = lib.ma_decode_memory(data, len(data), ffi.addressof(decoder_config), frames, memory)
if result != lib.MA_SUCCESS:
raise DecodeError("failed to decode data", result)
buffer = ffi.buffer(memory[0], frames[0] * nchannels * sample_width)
samples.frombytes(buffer)
lib.ma_free(memory[0], ffi.NULL)
return DecodedSoundFile("<memory>", nchannels, sample_rate, output_format, samples)
def _samples_stream_generator(frames_to_read: int, nchannels: int, output_format: SampleFormat,
decoder: ffi.CData, data: Any,
on_close: Optional[Callable] = None) -> Generator[array.array, int, None]:
_reference = data # make sure any data passed in is not garbage collected
sample_width = width_from_format(output_format)
samples_proto = _array_proto_from_format(output_format)
allocated_buffer_frames = max(frames_to_read, 16384)
try:
with ffi.new("int8_t[]", allocated_buffer_frames * nchannels * sample_width) as decodebuffer:
buf_ptr = ffi.cast("void *", decodebuffer)
want_frames = (yield samples_proto) or frames_to_read
source = None # type: Optional[StreamableSource]
if decoder.pUserData != ffi.NULL:
source = ffi.from_handle(decoder.pUserData)
while True:
if want_frames > allocated_buffer_frames:
raise MiniaudioError("wanted to read more frames than storage was allocated for ({} vs {})"
.format(want_frames, allocated_buffer_frames))
num_frames = 0
with ffi.new("ma_uint64 *") as frames_read:
try:
result = lib.ma_decoder_read_pcm_frames(decoder, buf_ptr, want_frames, frames_read)
except Exception as x:
raise DecodeError("error in ma_decoder_read_pcm_frames") from x
else:
if result == lib.MA_SUCCESS:
num_frames = frames_read[0]