Module pyaudio
[frames] | no frames]

Source Code for Module pyaudio

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