Debian Codegraph @

docs/audioop.rst

raw
1 :mod:`audioop` --- Manipulate raw audio data
2 ============================================
3
4 .. module:: audioop
5 :synopsis: Manipulate raw audio data.
6
7 .. note::
8 This is an LTS port of audio, which was scheduled for deprecation in Python 3.11
9 and later removed in Python 3.13. See :pep:`PEP 594 <594#audioop>` for details.
10
11 --------------
12
13 The :mod:`audioop` module contains some useful operations on sound fragments.
14 It operates on sound fragments consisting of signed integer samples 8, 16, 24
15 or 32 bits wide, stored in :term:`bytes-like objects <bytes-like object>`. All scalar items are
16 integers, unless specified otherwise.
17
18 .. versionchanged:: 3.4
19 Support for 24-bit samples was added.
20 All functions now accept any :term:`bytes-like object`.
21 String input now results in an immediate error.
22
23 .. index::
24 single: Intel/DVI ADPCM
25 single: ADPCM, Intel/DVI
26 single: a-LAW
27 single: u-LAW
28
29 This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.
30
31 .. This para is mostly here to provide an excuse for the index entries...
32
33 A few of the more complicated operations only take 16-bit samples, otherwise the
34 sample size (in bytes) is always a parameter of the operation.
35
36 The module defines the following variables and functions:
37
38
39 .. exception:: error
40
41 This exception is raised on all errors, such as unknown number of bytes per
42 sample, etc.
43
44
45 .. function:: add(fragment1, fragment2, width)
46
47 Return a fragment which is the addition of the two samples passed as parameters.
48 *width* is the sample width in bytes, either ``1``, ``2``, ``3`` or ``4``. Both
49 fragments should have the same length. Samples are truncated in case of overflow.
50
51
52 .. function:: adpcm2lin(adpcmfragment, width, state)
53
54 Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the
55 description of :func:`lin2adpcm` for details on ADPCM coding. Return a tuple
56 ``(sample, newstate)`` where the sample has the width specified in *width*.
57
58
59 .. function:: alaw2lin(fragment, width)
60
61 Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
62 a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
63 width of the output fragment here.
64
65
66 .. function:: avg(fragment, width)
67
68 Return the average over all samples in the fragment.
69
70
71 .. function:: avgpp(fragment, width)
72
73 Return the average peak-peak value over all samples in the fragment. No
74 filtering is done, so the usefulness of this routine is questionable.
75
76
77 .. function:: bias(fragment, width, bias)
78
79 Return a fragment that is the original fragment with a bias added to each
80 sample. Samples wrap around in case of overflow.
81
82
83 .. function:: byteswap(fragment, width)
84
85 "Byteswap" all samples in a fragment and returns the modified fragment.
86 Converts big-endian samples to little-endian and vice versa.
87
88 .. versionadded:: 3.4
89
90
91 .. function:: cross(fragment, width)
92
93 Return the number of zero crossings in the fragment passed as an argument.
94
95
96 .. function:: findfactor(fragment, reference)
97
98 Return a factor *F* such that ``rms(add(fragment, mul(reference, -F)))`` is
99 minimal, i.e., return the factor with which you should multiply *reference* to
100 make it match as well as possible to *fragment*. The fragments should both
101 contain 2-byte samples.
102
103 The time taken by this routine is proportional to ``len(fragment)``.
104
105
106 .. function:: findfit(fragment, reference)
107
108 Try to match *reference* as well as possible to a portion of *fragment* (which
109 should be the longer fragment). This is (conceptually) done by taking slices
110 out of *fragment*, using :func:`findfactor` to compute the best match, and
111 minimizing the result. The fragments should both contain 2-byte samples.
112 Return a tuple ``(offset, factor)`` where *offset* is the (integer) offset into
113 *fragment* where the optimal match started and *factor* is the (floating-point)
114 factor as per :func:`findfactor`.
115
116
117 .. function:: findmax(fragment, length)
118
119 Search *fragment* for a slice of length *length* samples (not bytes!) with
120 maximum energy, i.e., return *i* for which ``rms(fragment[i*2:(i+length)*2])``
121 is maximal. The fragments should both contain 2-byte samples.
122
123 The routine takes time proportional to ``len(fragment)``.
124
125
126 .. function:: getsample(fragment, width, index)
127
128 Return the value of sample *index* from the fragment.
129
130
131 .. function:: lin2adpcm(fragment, width, state)
132
133 Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive
134 coding scheme, whereby each 4 bit number is the difference between one sample
135 and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has
136 been selected for use by the IMA, so it may well become a standard.
137
138 *state* is a tuple containing the state of the coder. The coder returns a tuple
139 ``(adpcmfrag, newstate)``, and the *newstate* should be passed to the next call
140 of :func:`lin2adpcm`. In the initial call, ``None`` can be passed as the state.
141 *adpcmfrag* is the ADPCM coded fragment packed 2 4-bit values per byte.
142
143
144 .. function:: lin2alaw(fragment, width)
145
146 Convert samples in the audio fragment to a-LAW encoding and return this as a
147 bytes object. a-LAW is an audio encoding format whereby you get a dynamic
148 range of about 13 bits using only 8 bit samples. It is used by the Sun audio
149 hardware, among others.
150
151
152 .. function:: lin2lin(fragment, width, newwidth)
153
154 Convert samples between 1-, 2-, 3- and 4-byte formats.
155
156 .. note::
157
158 In some audio formats, such as .WAV files, 16, 24 and 32 bit samples are
159 signed, but 8 bit samples are unsigned. So when converting to 8 bit wide
160 samples for these formats, you need to also add 128 to the result::
161
162 new_frames = audioop.lin2lin(frames, old_width, 1)
163 new_frames = audioop.bias(new_frames, 1, 128)
164
165 The same, in reverse, has to be applied when converting from 8 to 16, 24
166 or 32 bit width samples.
167
168
169 .. function:: lin2ulaw(fragment, width)
170
171 Convert samples in the audio fragment to u-LAW encoding and return this as a
172 bytes object. u-LAW is an audio encoding format whereby you get a dynamic
173 range of about 14 bits using only 8 bit samples. It is used by the Sun audio
174 hardware, among others.
175
176
177 .. function:: max(fragment, width)
178
179 Return the maximum of the *absolute value* of all samples in a fragment.
180
181
182 .. function:: maxpp(fragment, width)
183
184 Return the maximum peak-peak value in the sound fragment.
185
186
187 .. function:: minmax(fragment, width)
188
189 Return a tuple consisting of the minimum and maximum values of all samples in
190 the sound fragment.
191
192
193 .. function:: mul(fragment, width, factor)
194
195 Return a fragment that has all samples in the original fragment multiplied by
196 the floating-point value *factor*. Samples are truncated in case of overflow.
197
198
199 .. function:: ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])
200
201 Convert the frame rate of the input fragment.
202
203 *state* is a tuple containing the state of the converter. The converter returns
204 a tuple ``(newfragment, newstate)``, and *newstate* should be passed to the next
205 call of :func:`ratecv`. The initial call should pass ``None`` as the state.
206
207 The *weightA* and *weightB* arguments are parameters for a simple digital filter
208 and default to ``1`` and ``0`` respectively.
209
210
211 .. function:: reverse(fragment, width)
212
213 Reverse the samples in a fragment and returns the modified fragment.
214
215
216 .. function:: rms(fragment, width)
217
218 Return the root-mean-square of the fragment, i.e. ``sqrt(sum(S_i^2)/n)``.
219
220 This is a measure of the power in an audio signal.
221
222
223 .. function:: tomono(fragment, width, lfactor, rfactor)
224
225 Convert a stereo fragment to a mono fragment. The left channel is multiplied by
226 *lfactor* and the right channel by *rfactor* before adding the two channels to
227 give a mono signal.
228
229
230 .. function:: tostereo(fragment, width, lfactor, rfactor)
231
232 Generate a stereo fragment from a mono fragment. Each pair of samples in the
233 stereo fragment are computed from the mono sample, whereby left channel samples
234 are multiplied by *lfactor* and right channel samples by *rfactor*.
235
236
237 .. function:: ulaw2lin(fragment, width)
238
239 Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
240 u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
241 width of the output fragment here.
242
243 Note that operations such as :func:`.mul` or :func:`.max` make no distinction
244 between mono and stereo fragments, i.e. all samples are treated equal. If this
245 is a problem the stereo fragment should be split into two mono fragments first
246 and recombined later. Here is an example of how to do that::
247
248 def mul_stereo(sample, width, lfactor, rfactor):
249 lsample = audioop.tomono(sample, width, 1, 0)
250 rsample = audioop.tomono(sample, width, 0, 1)
251 lsample = audioop.mul(lsample, width, lfactor)
252 rsample = audioop.mul(rsample, width, rfactor)
253 lsample = audioop.tostereo(lsample, width, 1, 0)
254 rsample = audioop.tostereo(rsample, width, 0, 1)
255 return audioop.add(lsample, rsample, width)
256
257 If you use the ADPCM coder to build network packets and you want your protocol
258 to be stateless (i.e. to be able to tolerate packet loss) you should not only
259 transmit the data but also the state. Note that you should send the *initial*
260 state (the one you passed to :func:`lin2adpcm`) along to the decoder, not the
261 final state (as returned by the coder). If you want to use
262 :class:`struct.Struct` to store the state in binary you can code the first
263 element (the predicted value) in 16 bits and the second (the delta index) in 8.
264
265 The ADPCM coders have never been tried against other ADPCM coders, only against
266 themselves. It could well be that I misinterpreted the standards in which case
267 they will not be interoperable with the respective standards.
268
269 The :func:`find\*` routines might look a bit funny at first sight. They are
270 primarily meant to do echo cancellation. A reasonably fast way to do this is to
271 pick the most energetic piece of the output sample, locate that in the input
272 sample and subtract the whole output sample from the input sample::
273
274 def echocancel(outputdata, inputdata):
275 pos = audioop.findmax(outputdata, 800) # one tenth second
276 out_test = outputdata[pos*2:]
277 in_test = inputdata[pos*2:]
278 ipos, factor = audioop.findfit(in_test, out_test)
279 # Optional (for better cancellation):
280 # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
281 # out_test)
282 prefill = '\0'*(pos+ipos)*2
283 postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
284 outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
285 return audioop.add(inputdata, outputdata, 2)