Module pyaudio
[frames] | no frames]

Source Code for Module pyaudio

   1  # PyAudio : Python Bindings for PortAudio. 
   2   
   3  # Copyright (c) 2006-2010 Hubert Pham 
   4   
   5  # Permission is hereby granted, free of charge, to any person obtaining 
   6  # a copy of this software and associated documentation files (the 
   7  # "Software"), to deal in the Software without restriction, including 
   8  # without limitation the rights to use, copy, modify, merge, publish, 
   9  # distribute, sublicense, and/or sell copies of the Software, and to 
  10  # permit persons to whom the Software is furnished to do so, subject to 
  11  # the following conditions: 
  12   
  13  # The above copyright notice and this permission notice shall be 
  14  # included in all copies or substantial portions of the Software. 
  15   
  16  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
  17  # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
  18  # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
  19  # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
  20  # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
  21  # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
  22  # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
  23   
  24   
  25  """ PyAudio : Python Bindings for PortAudio v19. 
  26   
  27  **These bindings only support PortAudio blocking mode.** 
  28   
  29  :var PaSampleFormat: 
  30    A list of all PortAudio ``PaSampleFormat`` value constants. 
  31   
  32    See: `paInt32`, `paInt24`, `paInt16`, `paInt8`, and `paUInt8`. 
  33   
  34  :var PaHostApiTypeId: 
  35    A list of all PortAudio ``PaHostApiTypeId`` constants. 
  36   
  37    See: `paInDevelopment`, `paDirectSound`, `paMME`, `paASIO`, 
  38    `paSoundManager`, `paCoreAudio`, `paOSS`, `paALSA`, `paAL`, *et al...* 
  39   
  40  :var PaErrorCode: 
  41    A list of all PortAudio ``PaErrorCode`` constants. 
  42    Typically, error code constants are included in Python 
  43    exception objects (as the second argument). 
  44   
  45    See: `paNoError`, `paNotInitialized`, `paUnanticipatedHostError`, 
  46    *et al...* 
  47   
  48  :group PortAudio Constants: 
  49    PaSampleFormat, PaHostApiTypeId, PaErrorCode 
  50   
  51  :group PaSampleFormat Values: 
  52    paFloat32, paInt32, paInt24, paInt16, 
  53    paInt8, paUInt8, paCustomFormat 
  54   
  55  :group PaHostApiTypeId Values: 
  56    paInDevelopment, paDirectSound, paMME, paASIO, 
  57    paSoundManager, paCoreAudio, paOSS, paALSA 
  58    paAL, paBeOS, paWDMKS, paJACK, paWASAPI, paNoDevice 
  59   
  60  :group PaErrorCode Values: 
  61    paNoError, 
  62    paNotInitialized, paUnanticipatedHostError, 
  63    paInvalidChannelCount, paInvalidSampleRate, 
  64    paInvalidDevice, paInvalidFlag, 
  65    paSampleFormatNotSupported, paBadIODeviceCombination, 
  66    paInsufficientMemory, paBufferTooBig, 
  67    paBufferTooSmall, paNullCallback, 
  68    paBadStreamPtr, paTimedOut, 
  69    paInternalError, paDeviceUnavailable, 
  70    paIncompatibleHostApiSpecificStreamInfo, paStreamIsStopped, 
  71    paStreamIsNotStopped, paInputOverflowed, 
  72    paOutputUnderflowed, paHostApiNotFound, 
  73    paInvalidHostApi, paCanNotReadFromACallbackStream, 
  74    paCanNotWriteToACallbackStream, 
  75    paCanNotReadFromAnOutputOnlyStream, 
  76    paCanNotWriteToAnInputOnlyStream, 
  77    paIncompatibleStreamHostApi 
  78   
  79  :group Stream Conversion Convenience Functions: 
  80    get_sample_size, get_format_from_width 
  81   
  82  :group PortAudio version: 
  83    get_portaudio_version, get_portaudio_version_text 
  84   
  85  :sort: PaSampleFormat, PaHostApiTypeId, PaErrorCode 
  86  :sort: PortAudio Constants, PaSampleFormat Values, 
  87         PaHostApiTypeId Values, PaErrorCode Values 
  88   
  89  """ 
  90   
  91  __author__ = "Hubert Pham" 
  92  __version__ = "0.2.4" 
  93  __docformat__ = "restructuredtext en" 
  94   
  95  import sys 
  96   
  97  # attempt to import PortAudio 
  98  try: 
  99      import _portaudio as pa 
 100  except ImportError: 
 101      print "Please build and install the PortAudio Python " +\ 
 102            "bindings first." 
 103      sys.exit(-1) 
 104   
 105   
 106  # Try to use Python 2.4's built in `set' 
 107  try: 
 108      a = set() 
 109      del a 
 110  except NameError: 
 111      from sets import Set as set 
 112   
 113  ############################################################ 
 114  # GLOBALS 
 115  ############################################################ 
 116   
 117  ##### PaSampleFormat Sample Formats ##### 
 118   
 119  paFloat32 = pa.paFloat32 
 120  paInt32 = pa.paInt32 
 121  paInt24 = pa.paInt24 
 122  paInt16 = pa.paInt16 
 123  paInt8 = pa.paInt8 
 124  paUInt8 = pa.paUInt8 
 125  paCustomFormat = pa.paCustomFormat 
 126   
 127  # group them together for epydoc 
 128  PaSampleFormat = ['paFloat32', 'paInt32', 'paInt24', 'paInt16', 
 129                    'paInt8', 'paUInt8', 'paCustomFormat'] 
 130   
 131   
 132  ###### HostAPI TypeId ##### 
 133   
 134  paInDevelopment = pa.paInDevelopment 
 135  paDirectSound = pa.paDirectSound 
 136  paMME = pa.paMME 
 137  paASIO = pa.paASIO 
 138  paSoundManager = pa.paSoundManager 
 139  paCoreAudio = pa.paCoreAudio 
 140  paOSS = pa.paOSS 
 141  paALSA = pa.paALSA 
 142  paAL = pa.paAL 
 143  paBeOS = pa.paBeOS 
 144  paWDMKS = pa.paWDMKS 
 145  paJACK = pa.paJACK 
 146  paWASAPI = pa.paWASAPI 
 147  paNoDevice = pa.paNoDevice 
 148   
 149  # group them together for epydoc 
 150  PaHostApiTypeId = ['paInDevelopment', 'paDirectSound', 'paMME', 
 151                     'paASIO', 'paSoundManager', 'paCoreAudio', 
 152                     'paOSS', 'paALSA', 'paAL', 'paBeOS', 
 153                     'paWDMKS', 'paJACK', 'paWASAPI', 'paNoDevice'] 
 154   
 155  ###### portaudio error codes ##### 
 156   
 157  paNoError = pa.paNoError 
 158  paNotInitialized = pa.paNotInitialized 
 159  paUnanticipatedHostError = pa.paUnanticipatedHostError 
 160  paInvalidChannelCount = pa.paInvalidChannelCount 
 161  paInvalidSampleRate = pa.paInvalidSampleRate 
 162  paInvalidDevice = pa.paInvalidDevice 
 163  paInvalidFlag = pa.paInvalidFlag 
 164  paSampleFormatNotSupported = pa.paSampleFormatNotSupported 
 165  paBadIODeviceCombination = pa.paBadIODeviceCombination 
 166  paInsufficientMemory = pa.paInsufficientMemory 
 167  paBufferTooBig = pa.paBufferTooBig 
 168  paBufferTooSmall = pa.paBufferTooSmall 
 169  paNullCallback = pa.paNullCallback 
 170  paBadStreamPtr = pa.paBadStreamPtr 
 171  paTimedOut = pa.paTimedOut 
 172  paInternalError = pa.paInternalError 
 173  paDeviceUnavailable = pa.paDeviceUnavailable 
 174  paIncompatibleHostApiSpecificStreamInfo = pa.paIncompatibleHostApiSpecificStreamInfo 
 175  paStreamIsStopped = pa.paStreamIsStopped 
 176  paStreamIsNotStopped = pa.paStreamIsNotStopped 
 177  paInputOverflowed = pa.paInputOverflowed 
 178  paOutputUnderflowed = pa.paOutputUnderflowed 
 179  paHostApiNotFound = pa.paHostApiNotFound 
 180  paInvalidHostApi = pa.paInvalidHostApi 
 181  paCanNotReadFromACallbackStream = pa.paCanNotReadFromACallbackStream 
 182  paCanNotWriteToACallbackStream = pa.paCanNotWriteToACallbackStream 
 183  paCanNotReadFromAnOutputOnlyStream = pa.paCanNotReadFromAnOutputOnlyStream 
 184  paCanNotWriteToAnInputOnlyStream = pa.paCanNotWriteToAnInputOnlyStream 
 185  paIncompatibleStreamHostApi = pa.paIncompatibleStreamHostApi 
 186   
 187  # group them together for epydoc 
 188  PaErrorCode = ['paNoError', 
 189                 'paNotInitialized', 'paUnanticipatedHostError', 
 190                 'paInvalidChannelCount', 'paInvalidSampleRate', 
 191                 'paInvalidDevice', 'paInvalidFlag', 
 192                 'paSampleFormatNotSupported', 'paBadIODeviceCombination', 
 193                 'paInsufficientMemory', 'paBufferTooBig', 
 194                 'paBufferTooSmall', 'paNullCallback', 
 195                 'paBadStreamPtr', 'paTimedOut', 
 196                 'paInternalError', 'paDeviceUnavailable', 
 197                 'paIncompatibleHostApiSpecificStreamInfo', 'paStreamIsStopped', 
 198                 'paStreamIsNotStopped', 'paInputOverflowed', 
 199                 'paOutputUnderflowed', 'paHostApiNotFound', 
 200                 'paInvalidHostApi', 'paCanNotReadFromACallbackStream', 
 201                 'paCanNotWriteToACallbackStream', 
 202                 'paCanNotReadFromAnOutputOnlyStream', 
 203                 'paCanNotWriteToAnInputOnlyStream', 
 204                 'paIncompatibleStreamHostApi'] 
 205   
 206  ############################################################ 
 207  # Convenience Functions 
 208  ############################################################ 
 209   
210 -def get_sample_size(format):
211 """ 212 Returns the size (in bytes) for the specified 213 sample `format` (a `PaSampleFormat` constant). 214 215 :param `format`: 216 PortAudio sample format constant `PaSampleFormat`. 217 218 :raises ValueError: Invalid specified `format`. 219 220 :rtype: int 221 """ 222 223 return pa.get_sample_size(format)
224
225 -def get_format_from_width(width, unsigned = True):
226 """ 227 Returns a PortAudio format constant for 228 the specified `width`. 229 230 :param `width`: 231 The desired sample width in bytes (1, 2, 3, or 4) 232 :param `unsigned`: 233 For 1 byte width, specifies signed or unsigned 234 format. 235 236 :raises ValueError: for invalid `width` 237 :rtype: `PaSampleFormat` 238 239 """ 240 241 if width == 1: 242 if unsigned: 243 return paUInt8 244 else: 245 return paInt8 246 elif width == 2: 247 return paInt16 248 elif width == 3: 249 return paInt24 250 elif width == 4: 251 return paFloat32 252 else: 253 raise ValueError, "Invalid width: %d" % width
254 255 256 ############################################################ 257 # Versioning 258 ############################################################ 259
260 -def get_portaudio_version():
261 """ 262 Returns portaudio version. 263 264 :rtype: str """ 265 266 return pa.get_version()
267
268 -def get_portaudio_version_text():
269 """ 270 Returns PortAudio version as a text string. 271 272 :rtype: str """ 273 274 return pa.get_version_text()
275 276 ############################################################ 277 # Wrapper around _portaudio Stream (Internal) 278 ############################################################ 279 280 # Note: See PyAudio class below for main export. 281
282 -class Stream:
283 284 """ 285 PortAudio Stream Wrapper. Use `PyAudio.open` to make a new 286 `Stream`. 287 288 :group Opening and Closing: 289 __init__, close 290 291 :group Stream Info: 292 get_input_latency, get_output_latency, get_time, get_cpu_load 293 294 :group Stream Management: 295 start_stream, stop_stream, is_active, is_stopped 296 297 :group Input Output: 298 write, read, get_read_available, get_write_available 299 300 """ 301
302 - def __init__(self, 303 PA_manager, 304 rate, 305 channels, 306 format, 307 input = False, 308 output = False, 309 input_device_index = None, 310 output_device_index = None, 311 frames_per_buffer = 1024, 312 start = True, 313 input_host_api_specific_stream_info = None, 314 output_host_api_specific_stream_info = None):
315 """ 316 Initialize a stream; this should be called by 317 `PyAudio.open`. A stream can either be input, output, or both. 318 319 320 :param `PA_manager`: A reference to the managing `PyAudio` instance 321 :param `rate`: Sampling rate 322 :param `channels`: Number of channels 323 :param `format`: Sampling size and format. See `PaSampleFormat`. 324 :param `input`: Specifies whether this is an input stream. 325 Defaults to False. 326 :param `output`: Specifies whether this is an output stream. 327 Defaults to False. 328 :param `input_device_index`: Index of Input Device to use. 329 Unspecified (or None) uses default device. 330 Ignored if `input` is False. 331 :param `output_device_index`: 332 Index of Output Device to use. 333 Unspecified (or None) uses the default device. 334 Ignored if `output` is False. 335 :param `frames_per_buffer`: Specifies the number of frames per buffer. 336 :param `start`: Start the stream running immediately. 337 Defaults to True. In general, there is no reason to set 338 this to false. 339 :param `input_host_api_specific_stream_info`: Specifies a host API 340 specific stream information data structure for input. 341 See `PaMacCoreStreamInfo`. 342 :param `output_host_api_specific_stream_info`: Specifies a host API 343 specific stream information data structure for output. 344 See `PaMacCoreStreamInfo`. 345 346 :raise ValueError: Neither input nor output 347 are set True. 348 349 """ 350 351 # no stupidity allowed 352 if not (input or output): 353 raise ValueError, \ 354 "Must specify an input or output " +\ 355 "stream." 356 357 # remember parent 358 self._parent = PA_manager 359 360 # remember if we are an: input, output (or both) 361 self._is_input = input 362 self._is_output = output 363 364 # are we running? 365 self._is_running = start 366 367 # remember some parameters 368 self._rate = rate 369 self._channels = channels 370 self._format = format 371 self._frames_per_buffer = frames_per_buffer 372 373 arguments = { 374 'rate' : rate, 375 'channels' : channels, 376 'format' : format, 377 'input' : input, 378 'output' : output, 379 'input_device_index' : input_device_index, 380 'output_device_index' : output_device_index, 381 'frames_per_buffer' : frames_per_buffer} 382 383 if input_host_api_specific_stream_info: 384 _l = input_host_api_specific_stream_info 385 arguments[ 386 'input_host_api_specific_stream_info' 387 ] = _l._get_host_api_stream_object() 388 389 if output_host_api_specific_stream_info: 390 _l = output_host_api_specific_stream_info 391 arguments[ 392 'output_host_api_specific_stream_info' 393 ] = _l._get_host_api_stream_object() 394 395 # calling pa.open returns a stream object 396 self._stream = pa.open(**arguments) 397 398 self._input_latency = self._stream.inputLatency 399 self._output_latency = self._stream.outputLatency 400 401 if self._is_running: 402 pa.start_stream(self._stream)
403 404
405 - def close(self):
406 """ Close the stream """ 407 408 pa.close(self._stream) 409 410 self._is_running = False 411 412 self._parent._remove_stream(self)
413 414 415 ############################################################ 416 # Stream Info 417 ############################################################ 418
419 - def get_input_latency(self):
420 """ 421 Return the input latency. 422 423 :rtype: float 424 """ 425 426 return self._stream.inputLatency
427 428
429 - def get_output_latency(self):
430 """ 431 Return the input latency. 432 433 :rtype: float 434 """ 435 436 return self._stream.outputLatency
437
438 - def get_time(self):
439 """ 440 Return stream time. 441 442 :rtype: float 443 444 """ 445 446 return pa.get_stream_time(self._stream)
447
448 - def get_cpu_load(self):
449 """ 450 Return the CPU load. 451 452 (Note: this is always 0.0 for the blocking API.) 453 454 :rtype: float 455 456 """ 457 458 return pa.get_stream_cpu_load(self._stream)
459 460 461 ############################################################ 462 # Stream Management 463 ############################################################ 464
465 - def start_stream(self):
466 """ Start the stream. """ 467 468 if self._is_running: 469 return 470 471 pa.start_stream(self._stream) 472 self._is_running = True
473
474 - def stop_stream(self):
475 476 """ Stop the stream. Once the stream is stopped, 477 one may not call write or read. However, one may 478 call start_stream to resume the stream. """ 479 480 if not self._is_running: 481 return 482 483 pa.stop_stream(self._stream) 484 self._is_running = False
485
486 - def is_active(self):
487 """ Returns whether the stream is active. 488 489 :rtype: bool """ 490 491 return pa.is_stream_active(self._stream)
492
493 - def is_stopped(self):
494 """ Returns whether the stream is stopped. 495 496 :rtype: bool """ 497 498 return pa.is_stream_stopped(self._stream)
499 500 501 ############################################################ 502 # Reading/Writing 503 ############################################################ 504
505 - def write(self, frames, num_frames = None, 506 exception_on_underflow = False):
507 508 """ 509 Write samples to the stream. 510 511 512 :param `frames`: 513 The frames of data. 514 :param `num_frames`: 515 The number of frames to write. 516 Defaults to None, in which this value will be 517 automatically computed. 518 :param `exception_on_underflow`: 519 Specifies whether an exception should be thrown 520 (or silently ignored) on buffer underflow. Defaults 521 to False for improved performance, especially on 522 slower platforms. 523 524 :raises IOError: if the stream is not an output stream 525 or if the write operation was unsuccessful. 526 527 :rtype: `None` 528 529 """ 530 531 if not self._is_output: 532 raise IOError("Not output stream", 533 paCanNotWriteToAnInputOnlyStream) 534 535 if num_frames == None: 536 # determine how many frames to read 537 width = get_sample_size(self._format) 538 num_frames = len(frames) / (self._channels * width) 539 #print len(frames), self._channels, self._width, num_frames 540 541 pa.write_stream(self._stream, frames, num_frames, 542 exception_on_underflow)
543 544
545 - def read(self, num_frames):
546 """ 547 Read samples from the stream. 548 549 550 :param `num_frames`: 551 The number of frames to read. 552 553 :raises IOError: if stream is not an input stream 554 or if the read operation was unsuccessful. 555 556 :rtype: str 557 558 """ 559 560 if not self._is_input: 561 raise IOError("Not input stream", 562 paCanNotReadFromAnOutputOnlyStream) 563 564 return pa.read_stream(self._stream, num_frames)
565
566 - def get_read_available(self):
567 """ 568 Return the number of frames that can be read 569 without waiting. 570 571 :rtype: int 572 """ 573 574 return pa.get_stream_read_available(self._stream)
575 576
577 - def get_write_available(self):
578 """ 579 Return the number of frames that can be written 580 without waiting. 581 582 :rtype: int 583 584 """ 585 586 return pa.get_stream_write_available(self._stream)
587 588 589 590 ############################################################ 591 # Main Export 592 ############################################################ 593
594 -class PyAudio:
595 596 """ 597 Python interface to PortAudio. Provides methods to: 598 - initialize and terminate PortAudio 599 - open and close streams 600 - query and inspect the available PortAudio Host APIs 601 - query and inspect the available PortAudio audio 602 devices 603 604 Use this class to open and close streams. 605 606 :group Stream Management: 607 open, close 608 609 :group Host API: 610 get_host_api_count, get_default_host_api_info, 611 get_host_api_info_by_type, get_host_api_info_by_index, 612 get_device_info_by_host_api_device_index 613 614 :group Device API: 615 get_device_count, is_format_supported, 616 get_default_input_device_info, 617 get_default_output_device_info, 618 get_device_info_by_index 619 620 :group Stream Format Conversion: 621 get_sample_size, get_format_from_width 622 623 """ 624 625 ############################################################ 626 # Initialization and Termination 627 ############################################################ 628
629 - def __init__(self):
630 631 """ Initialize PortAudio. """ 632 633 pa.initialize() 634 self._streams = set()
635
636 - def terminate(self):
637 638 """ Terminate PortAudio. 639 640 :attention: Be sure to call this method for every 641 instance of this object to release PortAudio resources. 642 """ 643 644 for stream in self._streams: 645 stream.close() 646 647 self._streams = set() 648 649 pa.terminate()
650 651 652 ############################################################ 653 # Stream Format 654 ############################################################ 655
656 - def get_sample_size(self, format):
657 """ 658 Returns the size (in bytes) for the specified 659 sample `format` (a `PaSampleFormat` constant). 660 661 662 :param `format`: 663 Sample format constant (`PaSampleFormat`). 664 665 :raises ValueError: Invalid specified `format`. 666 667 :rtype: int 668 """ 669 670 return pa.get_sample_size(format)
671 672
673 - def get_format_from_width(self, width, unsigned = True):
674 """ 675 Returns a PortAudio format constant for 676 the specified `width`. 677 678 :param `width`: 679 The desired sample width in bytes (1, 2, 3, or 4) 680 :param `unsigned`: 681 For 1 byte width, specifies signed or unsigned format. 682 683 :raises ValueError: for invalid `width` 684 685 :rtype: `PaSampleFormat` 686 """ 687 688 if width == 1: 689 if unsigned: 690 return paUInt8 691 else: 692 return paInt8 693 elif width == 2: 694 return paInt16 695 elif width == 3: 696 return paInt24 697 elif width == 4: 698 return paFloat32 699 else: 700 raise ValueError, "Invalid width: %d" % width
701 702 703 ############################################################ 704 # Stream Factory 705 ############################################################ 706
707 - def open(self, *args, **kwargs):
708 """ 709 Open a new stream. See constructor for 710 `Stream.__init__` for parameter details. 711 712 :returns: `Stream` """ 713 714 stream = Stream(self, *args, **kwargs) 715 self._streams.add(stream) 716 return stream
717 718
719 - def close(self, stream):
720 """ 721 Close a stream. Typically use `Stream.close` instead. 722 723 :param `stream`: 724 An instance of the `Stream` object. 725 726 :raises ValueError: if stream does not exist. 727 """ 728 729 if stream not in self._streams: 730 raise ValueError, "Stream `%s' not found" % str(stream) 731 732 stream.close()
733 734
735 - def _remove_stream(self, stream):
736 """ 737 Internal method. Removes a stream. 738 739 :param `stream`: 740 An instance of the `Stream` object. 741 742 """ 743 744 if stream in self._streams: 745 self._streams.remove(stream)
746 747 748 ############################################################ 749 # Host API Inspection 750 ############################################################ 751
752 - def get_host_api_count(self):
753 """ 754 Return the number of PortAudio Host APIs. 755 756 :rtype: int 757 """ 758 759 return pa.get_host_api_count()
760
761 - def get_default_host_api_info(self):
762 """ 763 Return a dictionary containing the default Host API 764 parameters. The keys of the dictionary mirror the data fields 765 of PortAudio's ``PaHostApiInfo`` structure. 766 767 :raises IOError: if no default input device available 768 :rtype: dict 769 770 """ 771 772 defaultHostApiIndex = pa.get_default_host_api() 773 return self.get_host_api_info_by_index(defaultHostApiIndex)
774 775
776 - def get_host_api_info_by_type(self, host_api_type):
777 """ 778 Return a dictionary containing the Host API parameters for the 779 host API specified by the `host_api_type`. The keys of the 780 dictionary mirror the data fields of PortAudio's ``PaHostApiInfo`` 781 structure. 782 783 784 :param `host_api_type`: 785 The desired Host API (`PaHostApiTypeId` constant). 786 787 :raises IOError: for invalid `host_api_type` 788 :rtype: dict 789 """ 790 791 index = pa.host_api_type_id_to_host_api_index(host_api_type) 792 return self.get_host_api_info_by_index(index)
793 794
795 - def get_host_api_info_by_index(self, host_api_index):
796 """ 797 Return a dictionary containing the Host API parameters for the 798 host API specified by the `host_api_index`. The keys of the 799 dictionary mirror the data fields of PortAudio's ``PaHostApiInfo`` 800 structure. 801 802 :param `host_api_index`: The host api index. 803 804 :raises IOError: for invalid `host_api_index` 805 806 :rtype: dict 807 """ 808 809 return self._make_host_api_dictionary( 810 host_api_index, 811 pa.get_host_api_info(host_api_index) 812 )
813
814 - def get_device_info_by_host_api_device_index(self, 815 host_api_index, 816 host_api_device_index):
817 """ 818 Return a dictionary containing the Device parameters for a 819 given Host API's n'th device. The keys of the dictionary 820 mirror the data fields of PortAudio's ``PaDeviceInfo`` structure. 821 822 823 :param `host_api_index`: 824 The Host API index number. 825 :param `host_api_device_index`: 826 The *n* 'th device of the host API. 827 828 :raises IOError: for invalid indices 829 830 :rtype: dict 831 """ 832 833 long_method_name = pa.host_api_device_index_to_device_index 834 device_index = long_method_name(host_api_index, 835 host_api_device_index) 836 return self.get_device_info_by_index(device_index)
837 838
839 - def _make_host_api_dictionary(self, index, host_api_struct):
840 """ 841 Internal method to create Host API dictionary 842 that mirrors PortAudio's ``PaHostApiInfo`` structure. 843 844 :rtype: dict 845 """ 846 847 return {'index' : index, 848 'structVersion' : host_api_struct.structVersion, 849 'type' : host_api_struct.type, 850 'name' : host_api_struct.name, 851 'deviceCount' : host_api_struct.deviceCount, 852 'defaultInputDevice' : host_api_struct.defaultInputDevice, 853 'defaultOutputDevice' : host_api_struct.defaultOutputDevice}
854 855 ############################################################ 856 # Device Inspection 857 ############################################################ 858
859 - def get_device_count(self):
860 """ 861 Return the number of PortAudio Host APIs. 862 863 :rtype: int 864 """ 865 866 return pa.get_device_count()
867
868 - def is_format_supported(self, rate, 869 input_device = None, 870 input_channels = None, 871 input_format = None, 872 output_device = None, 873 output_channels = None, 874 output_format = None):
875 """ 876 Check to see if specified device configuration 877 is supported. Returns True if the configuration 878 is supported; throws a ValueError exception otherwise. 879 880 :param `rate`: 881 Specifies the desired rate (in Hz) 882 :param `input_device`: 883 The input device index. Specify `None` (default) for 884 half-duplex output-only streams. 885 :param `input_channels`: 886 The desired number of input channels. Ignored if 887 `input_device` is not specified (or `None`). 888 :param `input_format`: 889 PortAudio sample format constant defined 890 in this module 891 :param `output_device`: 892 The output device index. Specify `None` (default) for 893 half-duplex input-only streams. 894 :param `output_channels`: 895 The desired number of output channels. Ignored if 896 `input_device` is not specified (or `None`). 897 :param `output_format`: 898 PortAudio sample format constant (`PaSampleFormat`). 899 900 :rtype: bool 901 :raises ValueError: tuple containing: 902 (error string, PortAudio error code `PaErrorCode`). 903 904 """ 905 906 if input_device == None and output_device == None: 907 raise ValueError("must specify stream format for input, " +\ 908 "output, or both", paInvalidDevice); 909 910 kwargs = {} 911 912 if input_device != None: 913 kwargs['input_device'] = input_device 914 kwargs['input_channels'] = input_channels 915 kwargs['input_format'] = input_format 916 917 if output_device != None: 918 kwargs['output_device'] = output_device 919 kwargs['output_channels'] = output_channels 920 kwargs['output_format'] = output_format 921 922 return pa.is_format_supported(rate, **kwargs)
923 924
926 """ 927 Return the default input Device parameters as a 928 dictionary. The keys of the dictionary mirror the data fields 929 of PortAudio's ``PaDeviceInfo`` structure. 930 931 :raises IOError: No default input device available. 932 :rtype: dict 933 """ 934 935 device_index = pa.get_default_input_device() 936 return self.get_device_info_by_index(device_index)
937
939 """ 940 Return the default output Device parameters as a 941 dictionary. The keys of the dictionary mirror the data fields 942 of PortAudio's ``PaDeviceInfo`` structure. 943 944 :raises IOError: No default output device available. 945 :rtype: dict 946 """ 947 948 device_index = pa.get_default_output_device() 949 return self.get_device_info_by_index(device_index)
950 951
952 - def get_device_info_by_index(self, device_index):
953 """ 954 Return the Device parameters for device specified in 955 `device_index` as a dictionary. The keys of the dictionary 956 mirror the data fields of PortAudio's ``PaDeviceInfo`` 957 structure. 958 959 :param `device_index`: The device index. 960 :raises IOError: Invalid `device_index`. 961 :rtype: dict 962 """ 963 964 return self._make_device_info_dictionary( 965 device_index, 966 pa.get_device_info(device_index) 967 )
968
969 - def _make_device_info_dictionary(self, index, device_info):
970 """ 971 Internal method to create Device Info dictionary 972 that mirrors PortAudio's ``PaDeviceInfo`` structure. 973 974 :rtype: dict 975 """ 976 977 return {'index' : index, 978 'structVersion' : device_info.structVersion, 979 'name' : device_info.name, 980 'hostApi' : device_info.hostApi, 981 'maxInputChannels' : device_info.maxInputChannels, 982 'maxOutputChannels' : device_info.maxOutputChannels, 983 'defaultLowInputLatency' : 984 device_info.defaultLowInputLatency, 985 'defaultLowOutputLatency' : 986 device_info.defaultLowOutputLatency, 987 'defaultHighInputLatency' : 988 device_info.defaultHighInputLatency, 989 'defaultHighOutputLatency' : 990 device_info.defaultHighOutputLatency, 991 'defaultSampleRate' : 992 device_info.defaultSampleRate 993 }
994 995 ###################################################################### 996 # Host Specific Stream Info 997 ###################################################################### 998 999 try: 1000 paMacCoreStreamInfo = pa.paMacCoreStreamInfo 1001 except AttributeError: 1002 pass 1003 else:
1004 - class PaMacCoreStreamInfo:
1005 1006 """ 1007 Mac OS X-only: PaMacCoreStreamInfo is a PortAudio Host API 1008 Specific Stream Info data structure for specifying Mac OS 1009 X-only settings. Instantiate this class (if desired) and pass 1010 the instance as the argument in `PyAudio.open` to parameters 1011 ``input_host_api_specific_stream_info`` or 1012 ``output_host_api_specific_stream_info``. (See `Stream.__init__`.) 1013 1014 :note: Mac OS X only. 1015 1016 :group Flags (constants): 1017 paMacCoreChangeDeviceParameters, paMacCoreFailIfConversionRequired, 1018 paMacCoreConversionQualityMin, paMacCoreConversionQualityMedium, 1019 paMacCoreConversionQualityLow, paMacCoreConversionQualityHigh, 1020 paMacCoreConversionQualityMax, paMacCorePlayNice, 1021 paMacCorePro, paMacCoreMinimizeCPUButPlayNice, paMacCoreMinimizeCPU 1022 1023 :group Settings: 1024 get_flags, get_channel_map 1025 1026 """ 1027 paMacCoreChangeDeviceParameters = pa.paMacCoreChangeDeviceParameters 1028 paMacCoreFailIfConversionRequired = pa.paMacCoreFailIfConversionRequired 1029 paMacCoreConversionQualityMin = pa.paMacCoreConversionQualityMin 1030 paMacCoreConversionQualityMedium = pa.paMacCoreConversionQualityMedium 1031 paMacCoreConversionQualityLow = pa.paMacCoreConversionQualityLow 1032 paMacCoreConversionQualityHigh = pa.paMacCoreConversionQualityHigh 1033 paMacCoreConversionQualityMax = pa.paMacCoreConversionQualityMax 1034 paMacCorePlayNice = pa.paMacCorePlayNice 1035 paMacCorePro = pa.paMacCorePro 1036 paMacCoreMinimizeCPUButPlayNice = pa.paMacCoreMinimizeCPUButPlayNice 1037 paMacCoreMinimizeCPU = pa.paMacCoreMinimizeCPU 1038
1039 - def __init__(self, flags = None, channel_map = None):
1040 """ 1041 Initialize with flags and channel_map. See PortAudio 1042 documentation for more details on these parameters; they are 1043 passed almost verbatim to the PortAudio library. 1044 1045 :param `flags`: paMacCore* flags OR'ed together. 1046 See `PaMacCoreStreamInfo`. 1047 :param `channel_map`: An array describing the channel mapping. 1048 See PortAudio documentation for usage. 1049 """ 1050 1051 kwargs = {"flags" : flags, 1052 "channel_map" : channel_map} 1053 1054 if flags == None: 1055 del kwargs["flags"] 1056 if channel_map == None: 1057 del kwargs["channel_map"] 1058 1059 self._paMacCoreStreamInfo = paMacCoreStreamInfo(**kwargs)
1060
1061 - def get_flags(self):
1062 """ 1063 Return the flags set at instantiation. 1064 1065 :rtype: int 1066 """ 1067 1068 return self._paMacCoreStreamInfo.flags
1069
1070 - def get_channel_map(self):
1071 """ 1072 Return the channel map set at instantiation. 1073 1074 :rtype: tuple or None 1075 """ 1076 1077 return self._paMacCoreStreamInfo.channel_map
1078
1080 """ Private method. """ 1081 1082 return self._paMacCoreStreamInfo
1083