@@ -173,7 +173,8 @@ def play(data, samplerate=None, mapping=None, blocking=False, loop=False,
173173
174174 """
175175 ctx = _CallbackContext (loop = loop )
176- ctx .frames = ctx .check_data (data , mapping , kwargs .get ('device' ))
176+ ctx .frames = ctx .check_data (
177+ data , mapping , kwargs .get ('device' ), kwargs .get ('extra_settings' ))
177178
178179 def callback (outdata , frames , time , status ):
179180 assert len (outdata ) == frames
@@ -359,7 +360,8 @@ def playrec(data, samplerate=None, channels=None, dtype=None,
359360
360361 """
361362 ctx = _CallbackContext ()
362- output_frames = ctx .check_data (data , output_mapping , kwargs .get ('device' ))
363+ output_frames = ctx .check_data (
364+ data , output_mapping , kwargs .get ('device' ), kwargs .get ('extra_settings' ))
363365 if dtype is None :
364366 dtype = ctx .data .dtype # ignore module defaults
365367 out , input_frames = ctx .check_out (out , output_frames , channels , dtype ,
@@ -690,7 +692,7 @@ def check_input_settings(device=None, channels=None, dtype=None,
690692 """
691693 parameters , dtype , samplesize , samplerate = _get_stream_parameters (
692694 'input' , device = device , channels = channels , dtype = dtype , latency = None ,
693- extra_settings = extra_settings , samplerate = samplerate )
695+ extra_settings = extra_settings , samplerate = samplerate , for_check = True )
694696 _check (_lib .Pa_IsFormatSupported (parameters , _ffi .NULL , samplerate ))
695697
696698
@@ -704,7 +706,7 @@ def check_output_settings(device=None, channels=None, dtype=None,
704706 """
705707 parameters , dtype , samplesize , samplerate = _get_stream_parameters (
706708 'output' , device = device , channels = channels , dtype = dtype , latency = None ,
707- extra_settings = extra_settings , samplerate = samplerate )
709+ extra_settings = extra_settings , samplerate = samplerate , for_check = True )
708710 _check (_lib .Pa_IsFormatSupported (_ffi .NULL , parameters , samplerate ))
709711
710712
@@ -808,6 +810,12 @@ def __init__(self, kind, samplerate=None, blocksize=None, device=None,
808810 if prime_output_buffers_using_stream_callback :
809811 stream_flags |= _lib .paPrimeOutputBuffersUsingStreamCallback
810812
813+ # Retain effective settings, including their C buffers, through close.
814+ if extra_settings is None :
815+ extra_settings = tuple (default .extra_settings )
816+ self ._extra_settings = (tuple (_split (extra_settings )),
817+ tuple (default .extra_settings ))
818+
811819 if kind == 'duplex' :
812820 idevice , odevice = _split (device )
813821 ichannels , ochannels = _split (channels )
@@ -2167,7 +2175,7 @@ class default:
21672175
21682176 See Also
21692177 --------
2170- AsioSettings, CoreAudioSettings, WasapiSettings
2178+ AlsaSettings, AsioSettings, CoreAudioSettings, WasapiSettings
21712179
21722180 """
21732181 samplerate : ... = None
@@ -2316,6 +2324,44 @@ class CallbackAbort(Exception):
23162324 """
23172325
23182326
2327+ class AlsaSettings :
2328+
2329+ def __init__ (self , device_string ):
2330+ """ALSA-specific settings for opening a PCM by address.
2331+
2332+ Use as ``extra_settings`` with ``device=None`` (or ``-2``).
2333+ The address overrides `default.device`. Channels and sample rate
2334+ must be supplied explicitly or through defaults. Streams also
2335+ require a numeric latency in seconds.
2336+
2337+ Parameters
2338+ ----------
2339+ device_string : str
2340+ ALSA PCM address, such as ``'hw:2,0'`` or a named PCM from the
2341+ ALSA configuration. It must be nonempty and contain no NUL.
2342+ An ALSA address is not a persistent hardware identifier.
2343+
2344+ Notes
2345+ -----
2346+ The stream's device attribute reports PortAudio's special value
2347+ ``-2``. Passing an explicit device index or name is an error.
2348+ For direct output with ``mapping=[1]`` in `play()` or `playrec()`,
2349+ use `OutputStream` with explicit channels instead; automatic
2350+ stereo detection requires enumerated device information.
2351+
2352+ """
2353+ if not isinstance (device_string , str ):
2354+ raise TypeError ('device_string must be a string' )
2355+ if not device_string or '\0 ' in device_string :
2356+ raise ValueError ('device_string must be nonempty and contain no NUL' )
2357+ _check (_lib .Pa_HostApiTypeIdToHostApiIndex (_lib .paALSA ),
2358+ 'ALSA host API is unavailable' )
2359+ self ._device_string = _ffi .new ('char[]' , device_string .encode ('utf-8' ))
2360+ self ._streaminfo : ... = _ffi .new ('PaAlsaStreamInfo*' )
2361+ _lib .PaAlsa_InitializeStreamInfo (self ._streaminfo )
2362+ self ._streaminfo .deviceString = self ._device_string
2363+
2364+
23192365class AsioSettings :
23202366
23212367 def __init__ (self , channel_selectors ):
@@ -2541,7 +2587,7 @@ def __init__(self, loop=False):
25412587 self .event = threading .Event ()
25422588 self .status = CallbackFlags ()
25432589
2544- def check_data (self , data , mapping , device ):
2590+ def check_data (self , data , mapping , device , extra_settings = None ):
25452591 """Check data and output mapping."""
25462592 import numpy as np
25472593 data = np .asarray (data )
@@ -2563,6 +2609,13 @@ def check_data(self, data, mapping, device):
25632609 # first two channels, which is unexpected when specifying mapping=[1].
25642610 # In this case, we play silence on the second channel, but only if the
25652611 # device actually supports a second channel:
2612+ effective_settings = (default .extra_settings if extra_settings is None
2613+ else extra_settings )
2614+ if (mapping_is_explicit and np .array_equal (mapping , [0 ]) and
2615+ isinstance (_select_input_or_output (effective_settings , 'output' ),
2616+ AlsaSettings )):
2617+ raise ValueError ('For ALSA direct output mapping=[1], use '
2618+ 'OutputStream with explicit channels' )
25662619 if (mapping_is_explicit and np .array_equal (mapping , [0 ]) and
25672620 query_devices (device , 'output' )['max_output_channels' ] >= 2 ):
25682621 channels = 2
@@ -2730,12 +2783,22 @@ def _check_dtype(dtype):
27302783
27312784
27322785def _get_stream_parameters (kind , device , channels , dtype , latency ,
2733- extra_settings : ..., samplerate ):
2786+ extra_settings : ..., samplerate , * , for_check = False ):
27342787 """Get parameters for one direction (input or output) of a stream."""
27352788 assert kind in ('input' , 'output' )
2736- if device is None :
2737- device = default .device
2738- device = _get_device_id (device , kind , raise_on_error = True )
2789+ if extra_settings is None :
2790+ extra_settings = default .extra_settings
2791+ extra_settings = _select_input_or_output (extra_settings , kind )
2792+ direct_alsa = isinstance (extra_settings , AlsaSettings )
2793+ if direct_alsa :
2794+ device = _select_input_or_output (device , kind )
2795+ if device is not None and device != - 2 :
2796+ raise ValueError ('AlsaSettings conflicts with an explicit device' )
2797+ device = _lib .paUseHostApiSpecificDeviceSpecification
2798+ else :
2799+ if device is None :
2800+ device = default .device
2801+ device = _get_device_id (device , kind , raise_on_error = True )
27392802 if channels is None :
27402803 channels = default .channels
27412804 channels = _select_input_or_output (channels , kind )
@@ -2745,15 +2808,33 @@ def _get_stream_parameters(kind, device, channels, dtype, latency,
27452808 if latency is None :
27462809 latency = default .latency
27472810 latency = _select_input_or_output (latency , kind )
2748- if extra_settings is None :
2749- extra_settings = default .extra_settings
2750- extra_settings = _select_input_or_output (extra_settings , kind )
27512811 if samplerate is None :
27522812 samplerate = default .samplerate
27532813
2754- info = query_devices (device )
2755- if channels is None :
2756- channels = info ['max_' + kind + '_channels' ]
2814+ if direct_alsa :
2815+ import math
2816+ import numbers
2817+ if (isinstance (channels , bool ) or
2818+ not isinstance (channels , numbers .Integral ) or channels < 1 ):
2819+ raise ValueError ('AlsaSettings requires a positive channel count' )
2820+ if (isinstance (samplerate , bool ) or
2821+ not isinstance (samplerate , numbers .Real ) or
2822+ not math .isfinite (samplerate ) or samplerate <= 0 ):
2823+ raise ValueError ('AlsaSettings requires a positive finite sample rate' )
2824+ if for_check :
2825+ latency = 0.0 # Pa_IsFormatSupported ignores suggested latency.
2826+ elif (isinstance (latency , bool ) or
2827+ not isinstance (latency , numbers .Real ) or
2828+ not math .isfinite (latency ) or latency < 0 ):
2829+ raise ValueError ('AlsaSettings requires finite numeric latency >= 0' )
2830+ else :
2831+ info = query_devices (device )
2832+ if channels is None :
2833+ channels = info ['max_' + kind + '_channels' ]
2834+ if latency in ('low' , 'high' ):
2835+ latency = info ['default_' + latency + '_' + kind + '_latency' ]
2836+ if samplerate is None :
2837+ samplerate = info ['default_samplerate' ]
27572838 try :
27582839 # If NumPy is available, get canonical dtype name
27592840 dtype = _sys .modules ['numpy' ].dtype (dtype ).name
@@ -2764,10 +2845,6 @@ def _get_stream_parameters(kind, device, channels, dtype, latency,
27642845 except KeyError as e :
27652846 raise ValueError ('Invalid ' + kind + ' sample format' ) from e
27662847 samplesize = _check (_lib .Pa_GetSampleSize (sampleformat ))
2767- if latency in ('low' , 'high' ):
2768- latency = info ['default_' + latency + '_' + kind + '_latency' ]
2769- if samplerate is None :
2770- samplerate = info ['default_samplerate' ]
27712848 parameters : ... = _ffi .new ('PaStreamParameters*' , (
27722849 device , channels , sampleformat , latency ,
27732850 extra_settings ._streaminfo if extra_settings else _ffi .NULL ))
0 commit comments