comparison tests/test_util.py @ 157:682bf4477fae

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