amine@157
|
1 import math
|
amine@157
|
2 from array import array
|
amine@157
|
3 from auditok.io import DATA_FORMAT
|
amine@157
|
4
|
amine@157
|
5
|
amine@157
|
6 def _sample_generator(*data_buffers):
|
amine@157
|
7 """
|
amine@157
|
8 Takes a list of many mono audio data buffers and makes a sample generator
|
amine@157
|
9 of interleaved audio samples, one sample from each channel. The resulting
|
amine@157
|
10 generator can be used to build a multichannel audio buffer.
|
amine@157
|
11 >>> gen = _sample_generator("abcd", "ABCD")
|
amine@157
|
12 >>> list(gen)
|
amine@157
|
13 ["a", "A", "b", "B", "c", "C", "d", "D"]
|
amine@157
|
14 """
|
amine@157
|
15 frame_gen = zip(*data_buffers)
|
amine@157
|
16 return (sample for frame in frame_gen for sample in frame)
|
amine@157
|
17
|
amine@157
|
18
|
amine@157
|
19 def _generate_pure_tone(
|
amine@157
|
20 frequency, duration_sec=1, sampling_rate=16000, sample_width=2, volume=1e4
|
amine@157
|
21 ):
|
amine@157
|
22 """
|
amine@157
|
23 Generates a pure tone with the given frequency.
|
amine@157
|
24 """
|
amine@157
|
25 assert frequency <= sampling_rate / 2
|
amine@157
|
26 max_value = (2 ** (sample_width * 8) // 2) - 1
|
amine@157
|
27 if volume > max_value:
|
amine@157
|
28 volume = max_value
|
amine@157
|
29 fmt = DATA_FORMAT[sample_width]
|
amine@157
|
30 total_samples = int(sampling_rate * duration_sec)
|
amine@157
|
31 step = frequency / sampling_rate
|
amine@157
|
32 two_pi_step = 2 * math.pi * step
|
amine@157
|
33 data = array(
|
amine@157
|
34 fmt,
|
amine@157
|
35 (
|
amine@157
|
36 int(math.sin(two_pi_step * i) * volume)
|
amine@157
|
37 for i in range(total_samples)
|
amine@157
|
38 ),
|
amine@157
|
39 )
|
amine@157
|
40 return data
|
amine@157
|
41
|
amine@157
|
42
|
amine@157
|
43 PURE_TONE_DICT = {
|
amine@157
|
44 freq: _generate_pure_tone(freq, 1, 16000, 2) for freq in (400, 800, 1600)
|
amine@157
|
45 }
|
amine@157
|
46 PURE_TONE_DICT.update(
|
amine@157
|
47 {
|
amine@157
|
48 freq: _generate_pure_tone(freq, 0.1, 16000, 2)
|
amine@157
|
49 for freq in (600, 1150, 2400, 7220)
|
amine@157
|
50 }
|
amine@157
|
51 )
|