Module pyaudio
[frames] | no frames]

Source Code for Module pyaudio

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