-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathsounddevice.py
More file actions
2932 lines (2433 loc) · 106 KB
/
sounddevice.py
File metadata and controls
2932 lines (2433 loc) · 106 KB
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
# Copyright (c) 2015-2017 Matthias Geier
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Play and Record Sound with Python.
http://python-sounddevice.readthedocs.io/
"""
__version__ = '0.3.7'
import atexit as _atexit
from cffi import FFI as _FFI
import os as _os
import platform as _platform
import sys as _sys
_ffi = _FFI()
_ffi.cdef("""
int Pa_GetVersion( void );
const char* Pa_GetVersionText( void );
typedef int PaError;
typedef enum PaErrorCode
{
paNoError = 0,
paNotInitialized = -10000,
paUnanticipatedHostError,
paInvalidChannelCount,
paInvalidSampleRate,
paInvalidDevice,
paInvalidFlag,
paSampleFormatNotSupported,
paBadIODeviceCombination,
paInsufficientMemory,
paBufferTooBig,
paBufferTooSmall,
paNullCallback,
paBadStreamPtr,
paTimedOut,
paInternalError,
paDeviceUnavailable,
paIncompatibleHostApiSpecificStreamInfo,
paStreamIsStopped,
paStreamIsNotStopped,
paInputOverflowed,
paOutputUnderflowed,
paHostApiNotFound,
paInvalidHostApi,
paCanNotReadFromACallbackStream,
paCanNotWriteToACallbackStream,
paCanNotReadFromAnOutputOnlyStream,
paCanNotWriteToAnInputOnlyStream,
paIncompatibleStreamHostApi,
paBadBufferPtr
} PaErrorCode;
const char *Pa_GetErrorText( PaError errorCode );
PaError Pa_Initialize( void );
PaError Pa_Terminate( void );
typedef int PaDeviceIndex;
#define paNoDevice -1
#define paUseHostApiSpecificDeviceSpecification -2
typedef int PaHostApiIndex;
PaHostApiIndex Pa_GetHostApiCount( void );
PaHostApiIndex Pa_GetDefaultHostApi( void );
typedef enum PaHostApiTypeId
{
paInDevelopment=0,
paDirectSound=1,
paMME=2,
paASIO=3,
paSoundManager=4,
paCoreAudio=5,
paOSS=7,
paALSA=8,
paAL=9,
paBeOS=10,
paWDMKS=11,
paJACK=12,
paWASAPI=13,
paAudioScienceHPI=14
} PaHostApiTypeId;
typedef struct PaHostApiInfo
{
int structVersion;
PaHostApiTypeId type;
const char *name;
int deviceCount;
PaDeviceIndex defaultInputDevice;
PaDeviceIndex defaultOutputDevice;
} PaHostApiInfo;
const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi );
PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type );
PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi,
int hostApiDeviceIndex );
typedef struct PaHostErrorInfo{
PaHostApiTypeId hostApiType;
long errorCode;
const char *errorText;
}PaHostErrorInfo;
const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void );
PaDeviceIndex Pa_GetDeviceCount( void );
PaDeviceIndex Pa_GetDefaultInputDevice( void );
PaDeviceIndex Pa_GetDefaultOutputDevice( void );
typedef double PaTime;
typedef unsigned long PaSampleFormat;
#define paFloat32 0x00000001
#define paInt32 0x00000002
#define paInt24 0x00000004
#define paInt16 0x00000008
#define paInt8 0x00000010
#define paUInt8 0x00000020
#define paCustomFormat 0x00010000
#define paNonInterleaved 0x80000000
typedef struct PaDeviceInfo
{
int structVersion;
const char *name;
PaHostApiIndex hostApi;
int maxInputChannels;
int maxOutputChannels;
PaTime defaultLowInputLatency;
PaTime defaultLowOutputLatency;
PaTime defaultHighInputLatency;
PaTime defaultHighOutputLatency;
double defaultSampleRate;
} PaDeviceInfo;
const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );
typedef struct PaStreamParameters
{
PaDeviceIndex device;
int channelCount;
PaSampleFormat sampleFormat;
PaTime suggestedLatency;
void *hostApiSpecificStreamInfo;
} PaStreamParameters;
#define paFormatIsSupported 0
PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
double sampleRate );
typedef void PaStream;
#define paFramesPerBufferUnspecified 0
typedef unsigned long PaStreamFlags;
#define paNoFlag 0
#define paClipOff 0x00000001
#define paDitherOff 0x00000002
#define paNeverDropInput 0x00000004
#define paPrimeOutputBuffersUsingStreamCallback 0x00000008
#define paPlatformSpecificFlags 0xFFFF0000
typedef struct PaStreamCallbackTimeInfo{
PaTime inputBufferAdcTime;
PaTime currentTime;
PaTime outputBufferDacTime;
} PaStreamCallbackTimeInfo;
typedef unsigned long PaStreamCallbackFlags;
#define paInputUnderflow 0x00000001
#define paInputOverflow 0x00000002
#define paOutputUnderflow 0x00000004
#define paOutputOverflow 0x00000008
#define paPrimingOutput 0x00000010
typedef enum PaStreamCallbackResult
{
paContinue=0,
paComplete=1,
paAbort=2
} PaStreamCallbackResult;
typedef int PaStreamCallback(
const void *input, void *output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData );
PaError Pa_OpenStream( PaStream** stream,
const PaStreamParameters *inputParameters,
const PaStreamParameters *outputParameters,
double sampleRate,
unsigned long framesPerBuffer,
PaStreamFlags streamFlags,
PaStreamCallback *streamCallback,
void *userData );
PaError Pa_OpenDefaultStream( PaStream** stream,
int numInputChannels,
int numOutputChannels,
PaSampleFormat sampleFormat,
double sampleRate,
unsigned long framesPerBuffer,
PaStreamCallback *streamCallback,
void *userData );
PaError Pa_CloseStream( PaStream *stream );
typedef void PaStreamFinishedCallback( void *userData );
PaError Pa_SetStreamFinishedCallback( PaStream *stream,
PaStreamFinishedCallback* streamFinishedCallback );
PaError Pa_StartStream( PaStream *stream );
PaError Pa_StopStream( PaStream *stream );
PaError Pa_AbortStream( PaStream *stream );
PaError Pa_IsStreamStopped( PaStream *stream );
PaError Pa_IsStreamActive( PaStream *stream );
typedef struct PaStreamInfo
{
int structVersion;
PaTime inputLatency;
PaTime outputLatency;
double sampleRate;
} PaStreamInfo;
const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream );
PaTime Pa_GetStreamTime( PaStream *stream );
double Pa_GetStreamCpuLoad( PaStream* stream );
PaError Pa_ReadStream( PaStream* stream,
void *buffer,
unsigned long frames );
PaError Pa_WriteStream( PaStream* stream,
const void *buffer,
unsigned long frames );
signed long Pa_GetStreamReadAvailable( PaStream* stream );
signed long Pa_GetStreamWriteAvailable( PaStream* stream );
PaHostApiTypeId Pa_GetStreamHostApiType( PaStream* stream );
PaError Pa_GetSampleSize( PaSampleFormat format );
void Pa_Sleep( long msec );
/* pa_mac_core.h */
typedef int32_t SInt32;
typedef struct
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
unsigned long flags;
SInt32 const * channelMap;
unsigned long channelMapSize;
} PaMacCoreStreamInfo;
void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags );
void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize );
const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input );
#define paMacCoreChangeDeviceParameters 0x01
#define paMacCoreFailIfConversionRequired 0x02
#define paMacCoreConversionQualityMin 0x0100
#define paMacCoreConversionQualityMedium 0x0200
#define paMacCoreConversionQualityLow 0x0300
#define paMacCoreConversionQualityHigh 0x0400
#define paMacCoreConversionQualityMax 0x0000
#define paMacCorePlayNice 0x00
#define paMacCorePro 0x01
#define paMacCoreMinimizeCPUButPlayNice 0x0100
#define paMacCoreMinimizeCPU 0x0101
/* pa_win_waveformat.h */
typedef unsigned long PaWinWaveFormatChannelMask;
/* pa_asio.h */
#define paAsioUseChannelSelectors 0x01
typedef struct PaAsioStreamInfo
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
unsigned long flags;
int *channelSelectors;
} PaAsioStreamInfo;
/* pa_win_wasapi.h */
typedef enum PaWasapiFlags
{
paWinWasapiExclusive = 1,
paWinWasapiRedirectHostProcessor = 2,
paWinWasapiUseChannelMask = 4,
paWinWasapiPolling = 8,
paWinWasapiThreadPriority = 16
} PaWasapiFlags;
typedef void (*PaWasapiHostProcessorCallback) (
void *inputBuffer, long inputFrames,
void *outputBuffer, long outputFrames, void *userData);
typedef enum PaWasapiThreadPriority
{
eThreadPriorityNone = 0,
eThreadPriorityAudio,
eThreadPriorityCapture,
eThreadPriorityDistribution,
eThreadPriorityGames,
eThreadPriorityPlayback,
eThreadPriorityProAudio,
eThreadPriorityWindowManager
} PaWasapiThreadPriority;
typedef enum PaWasapiStreamCategory
{
eAudioCategoryOther = 0,
eAudioCategoryCommunications = 3,
eAudioCategoryAlerts = 4,
eAudioCategorySoundEffects = 5,
eAudioCategoryGameEffects = 6,
eAudioCategoryGameMedia = 7,
eAudioCategoryGameChat = 8,
eAudioCategorySpeech = 9,
eAudioCategoryMovie = 10,
eAudioCategoryMedia = 11
} PaWasapiStreamCategory;
typedef enum PaWasapiStreamOption
{
eStreamOptionNone = 0,
eStreamOptionRaw = 1,
eStreamOptionMatchFormat = 2
} PaWasapiStreamOption;
typedef struct PaWasapiStreamInfo
{
unsigned long size;
PaHostApiTypeId hostApiType;
unsigned long version;
unsigned long flags;
PaWinWaveFormatChannelMask channelMask;
PaWasapiHostProcessorCallback hostProcessorOutput;
PaWasapiHostProcessorCallback hostProcessorInput;
PaWasapiThreadPriority threadPriority;
PaWasapiStreamCategory streamCategory;
PaWasapiStreamOption streamOption;
} PaWasapiStreamInfo;
""")
try:
_lib = _ffi.dlopen('portaudio')
except OSError:
if _platform.system() == 'Darwin':
_libname = 'libportaudio.dylib'
elif _platform.system() == 'Windows':
_libname = 'libportaudio' + _platform.architecture()[0] + '.dll'
else:
raise
_lib = _ffi.dlopen(_os.path.join(
_os.path.dirname(_os.path.abspath(__file__)),
'_sounddevice_data',
_libname
))
_sampleformats = {
'float32': _lib.paFloat32,
'int32': _lib.paInt32,
'int24': _lib.paInt24,
'int16': _lib.paInt16,
'int8': _lib.paInt8,
'uint8': _lib.paUInt8,
}
_initialized = 0
_last_callback = None
def play(data, samplerate=None, mapping=None, blocking=False, loop=False,
**kwargs):
"""Play back a NumPy array containing audio data.
Parameters
----------
data : array_like
Audio data to be played back. The columns of a two-dimensional
array are interpreted as channels, one-dimensional arrays are
treated as mono data.
The data types *float64*, *float32*, *int32*, *int16*, *int8*
and *uint8* can be used.
*float64* data is simply converted to *float32* before passing
it to PortAudio, because it's not supported natively.
mapping : array_like, optional
List of channel numbers (starting with 1) where the columns of
*data* shall be played back on. Must have the same length as
number of channels in *data* (except if *data* is mono, in which
case the signal is played back on all given output channels).
Each channel number may only appear once in *mapping*.
blocking : bool, optional
If ``False`` (the default), return immediately (but playback
continues in the background), if ``True``, wait until playback
is finished. A non-blocking invocation can be stopped with
`stop()` or turned into a blocking one with `wait()`.
loop : bool, optional
Play *data* in a loop.
Other Parameters
----------------
samplerate, **kwargs
All parameters of `OutputStream` -- except *channels*, *dtype*,
*callback* and *finished_callback* -- can be used.
See Also
--------
rec, playrec
"""
ctx = _CallbackContext(loop=loop)
ctx.frames = ctx.check_data(data, mapping, kwargs.get('device'))
def callback(outdata, frames, time, status):
assert len(outdata) == frames
ctx.callback_enter(status, outdata)
ctx.write_outdata(outdata)
ctx.callback_exit()
ctx.start_stream(OutputStream, samplerate, ctx.output_channels,
ctx.output_dtype, callback, blocking,
prime_output_buffers_using_stream_callback=False,
**kwargs)
def rec(frames=None, samplerate=None, channels=None, dtype=None,
out=None, mapping=None, blocking=False, **kwargs):
"""Record audio data into a NumPy array.
Parameters
----------
frames : int, sometimes optional
Number of frames to record. Not needed if *out* is given.
channels : int, optional
Number of channels to record. Not needed if *mapping* or *out*
is given. The default value can be changed with
`default.channels`.
dtype : str or numpy.dtype, optional
Data type of the recording. Not needed if *out* is given.
The data types *float64*, *float32*, *int32*, *int16*, *int8*
and *uint8* can be used. For ``dtype='float64'``, audio data is
recorded in *float32* format and converted afterwards, because
it's not natively supported by PortAudio. The default value can
be changed with `default.dtype`.
mapping : array_like, optional
List of channel numbers (starting with 1) to record.
If *mapping* is given, *channels* is silently ignored.
blocking : bool, optional
If ``False`` (the default), return immediately (but recording
continues in the background), if ``True``, wait until recording
is finished.
A non-blocking invocation can be stopped with `stop()` or turned
into a blocking one with `wait()`.
Returns
-------
numpy.ndarray or type(out)
The recorded data.
.. note:: By default (``blocking=False``), an array of data is
returned which is still being written to while recording!
The returned data is only valid once recording has stopped.
Use `wait()` to make sure the recording is finished.
Other Parameters
----------------
out : numpy.ndarray or subclass, optional
If *out* is specified, the recorded data is written into the
given array instead of creating a new array.
In this case, the arguments *frames*, *channels* and *dtype* are
silently ignored!
If *mapping* is given, its length must match the number of
channels in *out*.
samplerate, **kwargs
All parameters of `InputStream` -- except *callback* and
*finished_callback* -- can be used.
See Also
--------
play, playrec
"""
ctx = _CallbackContext()
ctx.frames = ctx.check_out(out, frames, channels, dtype, mapping)
def callback(indata, frames, time, status):
assert len(indata) == frames
ctx.callback_enter(status, indata)
ctx.read_indata(indata)
ctx.callback_exit()
ctx.start_stream(InputStream, samplerate, ctx.input_channels,
ctx.input_dtype, callback, blocking, **kwargs)
return ctx.out
def playrec(data, samplerate=None, channels=None, dtype=None,
out=None, input_mapping=None, output_mapping=None, blocking=False,
**kwargs):
"""Simultaneous playback and recording of NumPy arrays.
Parameters
----------
data : array_like
Audio data to be played back. See `play()`.
channels : int, sometimes optional
Number of input channels, see `rec()`.
The number of output channels is obtained from *data.shape*.
dtype : str or numpy.dtype, optional
Input data type, see `rec()`.
If *dtype* is not specified, it is taken from *data.dtype*
(i.e. `default.dtype` is ignored).
The output data type is obtained from *data.dtype* anyway.
input_mapping, output_mapping : array_like, optional
See the parameter *mapping* of `rec()` and `play()`,
respectively.
blocking : bool, optional
If ``False`` (the default), return immediately (but continue
playback/recording in the background), if ``True``, wait until
playback/recording is finished.
A non-blocking invocation can be stopped with `stop()` or turned
into a blocking one with `wait()`.
Returns
-------
numpy.ndarray or type(out)
The recorded data. See `rec()`.
Other Parameters
----------------
out : numpy.ndarray or subclass, optional
See `rec()`.
samplerate, **kwargs
All parameters of `Stream` -- except *channels*, *dtype*,
*callback* and *finished_callback* -- can be used.
See Also
--------
play, rec
"""
ctx = _CallbackContext()
output_frames = ctx.check_data(data, output_mapping, kwargs.get('device'))
if dtype is None:
dtype = ctx.data.dtype # ignore module defaults
input_frames = ctx.check_out(out, output_frames, channels, dtype,
input_mapping)
if input_frames != output_frames:
raise PortAudioError('len(data) != len(out)')
ctx.frames = input_frames
def callback(indata, outdata, frames, time, status):
assert len(indata) == len(outdata) == frames
ctx.callback_enter(status, indata)
ctx.read_indata(indata)
ctx.write_outdata(outdata)
ctx.callback_exit()
ctx.start_stream(Stream, samplerate,
(ctx.input_channels, ctx.output_channels),
(ctx.input_dtype, ctx.output_dtype),
callback, blocking,
prime_output_buffers_using_stream_callback=False,
**kwargs)
return ctx.out
def wait():
"""Wait for `play()`/`rec()`/`playrec()` to be finished.
Playback/recording can be stopped with a `KeyboardInterrupt`.
Returns
-------
CallbackFlags or None
If at least one buffer over-/underrun happened during the last
playback/recording, a `CallbackFlags` object is returned.
See Also
--------
get_status
"""
if _last_callback:
return _last_callback.wait()
def stop(ignore_errors=True):
"""Stop playback/recording.
This only stops `play()`, `rec()` and `playrec()`, but has no
influence on streams created with `Stream`, `InputStream`,
`OutputStream`, `RawStream`, `RawInputStream`, `RawOutputStream`.
"""
if _last_callback:
_last_callback.stream.close(ignore_errors)
def get_status():
"""Get info about over-/underflows in `play()`/`rec()`/`playrec()`.
Returns
-------
CallbackFlags
A `CallbackFlags` object that holds information about the last
invocation of `play()`, `rec()` or `playrec()`.
See Also
--------
wait
"""
if _last_callback:
return _last_callback.status
else:
raise RuntimeError('play()/rec()/playrec() was not called yet')
def get_stream():
"""Get a reference to the current stream.
This applies only to streams created by calls to `play()`, `rec()`
or `playrec()`.
Returns
-------
Stream
An `OutputStream`, `InputStream` or `Stream` associated with
the last invocation of `play()`, `rec()` or `playrec()`,
respectively.
"""
if _last_callback:
return _last_callback.stream
else:
raise RuntimeError('play()/rec()/playrec() was not called yet')
def query_devices(device=None, kind=None):
"""Return information about available devices.
Information and capabilities of PortAudio devices.
Devices may support input, output or both input and output.
To find the default input/output device(s), use `default.device`.
Parameters
----------
device : int or str, optional
Numeric device ID or device name substring(s).
If specified, information about only the given *device* is
returned in a single dictionary.
kind : {'input', 'output'}, optional
If *device* is not specified and *kind* is ``'input'`` or
``'output'``, a single dictionary is returned with information
about the default input or output device, respectively.
Returns
-------
dict or DeviceList
A dictionary with information about the given *device* or -- if
no arguments were specified -- a `DeviceList` containing one
dictionary for each available device.
The dictionaries have the following keys:
``'name'``
The name of the device.
``'hostapi'``
The ID of the corresponding host API. Use
`query_hostapis()` to get information about a host API.
``'max_input_channels'``, ``'max_output_channels'``
The maximum number of input/output channels supported by the
device. See `default.channels`.
``'default_low_input_latency'``, ``'default_low_output_latency'``
Default latency values for interactive performance.
This is used if `default.latency` (or the *latency* argument
of `playrec()`, `Stream` etc.) is set to ``'low'``.
``'default_high_input_latency'``, ``'default_high_output_latency'``
Default latency values for robust non-interactive
applications (e.g. playing sound files).
This is used if `default.latency` (or the *latency* argument
of `playrec()`, `Stream` etc.) is set to ``'high'``.
``'default_samplerate'``
The default sampling frequency of the device.
This is used if `default.samplerate` is not set.
Notes
-----
The list of devices can also be displayed in a terminal:
.. code-block:: sh
python3 -m sounddevice
Examples
--------
The returned `DeviceList` can be indexed and iterated over like any
sequence type (yielding the abovementioned dictionaries), but it
also has a special string representation which is shown when used in
an interactive Python session.
Each available device is listed on one line together with the
corresponding device ID, which can be assigned to `default.device`
or used as *device* argument in `play()`, `Stream` etc.
The first character of a line is ``>`` for the default input device,
``<`` for the default output device and ``*`` for the default
input/output device. After the device ID and the device name, the
corresponding host API name is displayed. In the end of each line,
the maximum number of input and output channels is shown.
On a GNU/Linux computer it might look somewhat like this:
>>> import sounddevice as sd
>>> sd.query_devices()
0 HDA Intel: ALC662 rev1 Analog (hw:0,0), ALSA (2 in, 2 out)
1 HDA Intel: ALC662 rev1 Digital (hw:0,1), ALSA (0 in, 2 out)
2 HDA Intel: HDMI 0 (hw:0,3), ALSA (0 in, 8 out)
3 sysdefault, ALSA (128 in, 128 out)
4 front, ALSA (0 in, 2 out)
5 surround40, ALSA (0 in, 2 out)
6 surround51, ALSA (0 in, 2 out)
7 surround71, ALSA (0 in, 2 out)
8 iec958, ALSA (0 in, 2 out)
9 spdif, ALSA (0 in, 2 out)
10 hdmi, ALSA (0 in, 8 out)
* 11 default, ALSA (128 in, 128 out)
12 dmix, ALSA (0 in, 2 out)
13 /dev/dsp, OSS (16 in, 16 out)
Note that ALSA provides access to some "real" and some "virtual"
devices. The latter sometimes have a ridiculously high number of
(virtual) inputs and outputs.
On macOS, you might get something similar to this:
>>> sd.query_devices()
0 Built-in Line Input, Core Audio (2 in, 0 out)
> 1 Built-in Digital Input, Core Audio (2 in, 0 out)
< 2 Built-in Output, Core Audio (0 in, 2 out)
3 Built-in Line Output, Core Audio (0 in, 2 out)
4 Built-in Digital Output, Core Audio (0 in, 2 out)
"""
if kind not in ('input', 'output', None):
raise ValueError('Invalid kind: {0!r}'.format(kind))
if device is None and kind is None:
return DeviceList(query_devices(i)
for i in range(_check(_lib.Pa_GetDeviceCount())))
device = _get_device_id(device, kind, raise_on_error=True)
info = _lib.Pa_GetDeviceInfo(device)
if not info:
raise PortAudioError('Error querying device {0}'.format(device))
assert info.structVersion == 2
name_bytes = _ffi.string(info.name)
try:
# We don't know beforehand if DirectSound and MME device names use
# 'utf-8' or 'mbcs' encoding. Let's try 'utf-8' first, because it more
# likely raises an exception on 'mbcs' data than vice versa, see also
# https://github.com/spatialaudio/python-sounddevice/issues/72.
# All other host APIs use 'utf-8' anyway.
name = name_bytes.decode('utf-8')
except UnicodeDecodeError:
if info.hostApi in (
_lib.Pa_HostApiTypeIdToHostApiIndex(_lib.paDirectSound),
_lib.Pa_HostApiTypeIdToHostApiIndex(_lib.paMME)):
name = name_bytes.decode('mbcs')
else:
raise
device_dict = {
'name': name,
'hostapi': info.hostApi,
'max_input_channels': info.maxInputChannels,
'max_output_channels': info.maxOutputChannels,
'default_low_input_latency': info.defaultLowInputLatency,
'default_low_output_latency': info.defaultLowOutputLatency,
'default_high_input_latency': info.defaultHighInputLatency,
'default_high_output_latency': info.defaultHighOutputLatency,
'default_samplerate': info.defaultSampleRate,
}
if kind and device_dict['max_' + kind + '_channels'] < 1:
raise ValueError(
'Not an {0} device: {1!r}'.format(kind, device_dict['name']))
return device_dict
def query_hostapis(index=None, name=None):
"""Return information about available host APIs.
Parameters
----------
index : int, optional
If specified, information about only the given host API *index*
is returned in a single dictionary.
name : str, optional
If specified, information about only the given host API *name*
is returned in a single dictionary.
Returns
-------
dict or tuple of dict
A dictionary with information about the given host API *index*
or -- if no *index* was specified -- a tuple containing one
dictionary for each available host API.
The dictionaries have the following keys:
``'name'``
The name of the host API.
``'devices'``
A list of device IDs belonging to the host API.
Use `query_devices()` to get information about a device.
``'default_input_device'``, ``'default_output_device'``
The device ID of the default input/output device of the host
API. If no default input/output device exists for the given
host API, this is -1.
.. note:: The overall default device(s) -- which can be
overwritten by assigning to `default.device` -- take(s)
precedence over `default.hostapi` and the information in
the abovementioned dictionaries.
See Also
--------
query_devices
"""
if name is not None:
if index is not None:
raise ValueError('May not specify both index and name')
hostapi_list = tuple(query_hostapis(i) for i in
range(_check(_lib.Pa_GetHostApiCount())))
hostapi_list = filter(lambda x: x['name'] == name, hostapi_list)
assert len(hostapi_list) <= 1
try:
return hostapi_list[0]
except IndexError:
raise PortAudioError('Host API {0!r} not found'.format(name))
if index is None:
return tuple(query_hostapis(i)
for i in range(_check(_lib.Pa_GetHostApiCount())))
info = _lib.Pa_GetHostApiInfo(index)
if not info:
raise PortAudioError('Error querying host API {0}'.format(index))
assert info.structVersion == 1
return {
'name': _ffi.string(info.name).decode(),
'devices': [_lib.Pa_HostApiDeviceIndexToDeviceIndex(index, i)
for i in range(info.deviceCount)],
'default_input_device': info.defaultInputDevice,
'default_output_device': info.defaultOutputDevice,
}
def check_input_settings(device=None, channels=None, dtype=None,
extra_settings=None, samplerate=None):
"""Check if given input device settings are supported.
All parameters are optional, `default` settings are used for any
unspecified parameters. If the settings are supported, the function
does nothing; if not, an exception is raised.
Parameters
----------
device : int or str, optional
Device ID or device name substring(s), see `default.device`.
channels : int, optional
Number of input channels, see `default.channels`.
dtype : str or numpy.dtype, optional
Data type for input samples, see `default.dtype`.
extra_settings : settings object, optional
This can be used for host-API-specific input settings.
See `default.extra_settings`.
samplerate : float, optional
Sampling frequency, see `default.samplerate`.
"""
parameters, dtype, samplesize, samplerate = _get_stream_parameters(
'input', device=device, channels=channels, dtype=dtype, latency=None,
extra_settings=extra_settings, samplerate=samplerate)
_check(_lib.Pa_IsFormatSupported(parameters, _ffi.NULL, samplerate))
def check_output_settings(device=None, channels=None, dtype=None,
extra_settings=None, samplerate=None):
"""Check if given output device settings are supported.
Same as `check_input_settings()`, just for output device
settings.
"""
parameters, dtype, samplesize, samplerate = _get_stream_parameters(
'output', device=device, channels=channels, dtype=dtype, latency=None,
extra_settings=extra_settings, samplerate=samplerate)
_check(_lib.Pa_IsFormatSupported(_ffi.NULL, parameters, samplerate))
def sleep(msec):
"""Put the caller to sleep for at least *msec* milliseconds.
The function may sleep longer than requested so don't rely on this
for accurate musical timing.
"""
_lib.Pa_Sleep(msec)
def get_portaudio_version():
"""Get version information for the PortAudio library.
Returns the release number and a textual description of the current
PortAudio build, e.g. ::
(1899, 'PortAudio V19-devel (built Feb 15 2014 23:28:00)')
"""
return _lib.Pa_GetVersion(), _ffi.string(_lib.Pa_GetVersionText()).decode()
class _StreamBase(object):
"""Direct or indirect base class for all stream classes."""
def __init__(self, kind, samplerate=None, blocksize=None, device=None,
channels=None, dtype=None, latency=None, extra_settings=None,
callback=None, finished_callback=None, clip_off=None,
dither_off=None, never_drop_input=None,
prime_output_buffers_using_stream_callback=None,
userdata=None, wrap_callback=None):
assert kind in ('input', 'output', 'duplex')
assert wrap_callback in ('array', 'buffer', None)
if blocksize is None:
blocksize = default.blocksize
if clip_off is None:
clip_off = default.clip_off
if dither_off is None:
dither_off = default.dither_off
if never_drop_input is None:
never_drop_input = default.never_drop_input
if prime_output_buffers_using_stream_callback is None:
prime_output_buffers_using_stream_callback = \
default.prime_output_buffers_using_stream_callback
stream_flags = _lib.paNoFlag
if clip_off:
stream_flags |= _lib.paClipOff
if dither_off:
stream_flags |= _lib.paDitherOff
if never_drop_input:
stream_flags |= _lib.paNeverDropInput
if prime_output_buffers_using_stream_callback:
stream_flags |= _lib.paPrimeOutputBuffersUsingStreamCallback
if kind == 'duplex':
idevice, odevice = _split(device)
ichannels, ochannels = _split(channels)
idtype, odtype = _split(dtype)
ilatency, olatency = _split(latency)
iextra, oextra = _split(extra_settings)
iparameters, idtype, isize, isamplerate = _get_stream_parameters(
'input', idevice, ichannels, idtype, ilatency, iextra,
samplerate)
oparameters, odtype, osize, osamplerate = _get_stream_parameters(
'output', odevice, ochannels, odtype, olatency, oextra,
samplerate)
self._dtype = idtype, odtype
self._device = iparameters.device, oparameters.device
self._channels = iparameters.channelCount, oparameters.channelCount
self._samplesize = isize, osize
if isamplerate != osamplerate:
raise PortAudioError(
'Input and output device must have the same samplerate')
else:
samplerate = isamplerate
else:
parameters, self._dtype, self._samplesize, samplerate = \
_get_stream_parameters(kind, device, channels, dtype, latency,
extra_settings, samplerate)
self._device = parameters.device
self._channels = parameters.channelCount
if kind == 'input':
iparameters = parameters
oparameters = _ffi.NULL
elif kind == 'output':
iparameters = _ffi.NULL
oparameters = parameters
ffi_callback = _ffi.callback('PaStreamCallback', error=_lib.paAbort)
if callback is None:
callback_ptr = _ffi.NULL
elif kind == 'input' and wrap_callback == 'buffer':
@ffi_callback
def callback_ptr(iptr, optr, frames, time, status, _):
data = _buffer(iptr, frames, self._channels, self._samplesize)
return _wrap_callback(callback, data, frames, time, status)
elif kind == 'input' and wrap_callback == 'array':
@ffi_callback
def callback_ptr(iptr, optr, frames, time, status, _):
data = _array(