0
# Convenience Functions
1
2
High-level functions for simple audio playback, recording, and simultaneous operations. These functions provide the easiest way to work with audio data using NumPy arrays, handling most of the complexity internally while offering essential control parameters.
3
4
## Capabilities
5
6
### Audio Playback
7
8
Play back NumPy arrays containing audio data with support for non-blocking operation, looping, and custom device mapping.
9
10
```python { .api }
11
def play(data, samplerate=None, mapping=None, blocking=False, loop=False, **kwargs):
12
"""
13
Play back NumPy array containing audio data.
14
15
Parameters:
16
- data (array_like): Audio data to play back
17
- samplerate (float, optional): Sample rate in Hz
18
- mapping (array_like, optional): Channel mapping to output devices
19
- blocking (bool): If True, wait until playback is finished
20
- loop (bool): If True, loop the audio indefinitely
21
- **kwargs: Additional parameters for stream creation
22
23
Returns:
24
None
25
"""
26
```
27
28
### Audio Recording
29
30
Record audio input into NumPy arrays with configurable duration, sample rate, channels, and data type.
31
32
```python { .api }
33
def rec(frames=None, samplerate=None, channels=None, dtype=None, out=None, mapping=None, blocking=False, **kwargs):
34
"""
35
Record audio into NumPy array.
36
37
Parameters:
38
- frames (int, optional): Number of frames to record
39
- samplerate (float, optional): Sample rate in Hz
40
- channels (int or array_like, optional): Number of input channels
41
- dtype (str or numpy.dtype, optional): Data type of output array
42
- out (numpy.ndarray, optional): Output array to write data into
43
- mapping (array_like, optional): Channel mapping from input devices
44
- blocking (bool): If True, wait until recording is finished (default: False)
45
- **kwargs: Additional parameters for stream creation
46
47
Returns:
48
numpy.ndarray: Recorded audio data
49
"""
50
```
51
52
### Simultaneous Playback and Recording
53
54
Perform simultaneous audio playback and recording, useful for real-time audio processing applications and system response measurements.
55
56
```python { .api }
57
def playrec(data, samplerate=None, channels=None, dtype=None, out=None, input_mapping=None, output_mapping=None, blocking=False, **kwargs):
58
"""
59
Simultaneous playback and recording.
60
61
Parameters:
62
- data (array_like): Audio data to play back
63
- samplerate (float, optional): Sample rate in Hz
64
- channels (int, optional): Number of input channels for recording
65
- dtype (str or numpy.dtype, optional): Data type of recorded output array
66
- out (numpy.ndarray, optional): Output array to write recorded data into
67
- input_mapping (array_like, optional): Channel mapping for input devices
68
- output_mapping (array_like, optional): Channel mapping for output devices
69
- blocking (bool): If True, wait until operation is finished (default: False)
70
- **kwargs: Additional parameters for stream creation
71
72
Returns:
73
numpy.ndarray or type(out): Recorded audio data
74
"""
75
```
76
77
### Operation Control
78
79
Control and monitor current audio operations with functions to wait for completion, stop operations, and check status.
80
81
```python { .api }
82
def wait(ignore_errors=True):
83
"""
84
Wait for current audio operation to complete.
85
86
Parameters:
87
- ignore_errors (bool): If True, ignore PortAudio errors
88
89
Returns:
90
CallbackFlags or None: Status information about buffer over-/underruns, or None
91
"""
92
93
def stop(ignore_errors=True):
94
"""
95
Stop current audio operation.
96
97
Parameters:
98
- ignore_errors (bool): If True, ignore PortAudio errors
99
100
Returns:
101
None
102
"""
103
104
def get_status():
105
"""
106
Get current playback/recording status.
107
108
Returns:
109
CallbackFlags: Object containing status flags for current operation
110
"""
111
112
def get_stream():
113
"""
114
Get currently active stream object.
115
116
Returns:
117
Stream, InputStream, or OutputStream: Current active stream object
118
"""
119
```
120
121
## Usage Examples
122
123
### Basic Recording and Playback
124
125
```python
126
import sounddevice as sd
127
import numpy as np
128
129
# Record 3 seconds of audio
130
duration = 3.0
131
samplerate = 44100
132
print("Recording...")
133
recording = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=1)
134
sd.wait() # Wait until recording is finished
135
print("Recording complete!")
136
137
# Play back the recorded audio
138
print("Playing back...")
139
sd.play(recording, samplerate=samplerate)
140
sd.wait() # Wait until playback is finished
141
print("Playback complete!")
142
```
143
144
### Non-blocking Operations
145
146
```python
147
import sounddevice as sd
148
import numpy as np
149
import time
150
151
# Start non-blocking playback
152
duration = 5.0
153
samplerate = 44100
154
t = np.linspace(0, duration, int(samplerate * duration))
155
audio = 0.5 * np.sin(2 * np.pi * 440 * t) # 440 Hz sine wave
156
157
sd.play(audio, samplerate=samplerate, blocking=False)
158
print("Audio started playing...")
159
160
# Do other work while audio plays
161
for i in range(5):
162
time.sleep(1)
163
status = sd.get_status()
164
print(f"Status: {status}")
165
166
sd.wait() # Wait for completion
167
print("Playback finished!")
168
```
169
170
### Simultaneous Playback and Recording
171
172
```python
173
import sounddevice as sd
174
import numpy as np
175
176
# Generate test signal
177
duration = 2.0
178
samplerate = 48000
179
frequency = 1000 # 1 kHz
180
t = np.linspace(0, duration, int(samplerate * duration))
181
test_signal = 0.5 * np.sin(2 * np.pi * frequency * t)
182
183
# Play test signal and record system response
184
print("Playing test signal and recording...")
185
recorded = sd.playrec(test_signal, samplerate=samplerate, channels=1)
186
sd.wait()
187
print("Operation complete!")
188
189
# Now 'recorded' contains the system's response to the test signal
190
print(f"Recorded {len(recorded)} samples")
191
```