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