Coverage for src/botadi/mokadi/mokadi_record.py: 10%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

48 statements  

1""" 

2@file 

3@brief Record a couple of seconds and returns the raw stream. 

4""" 

5import io 

6import wave 

7from pyquickhelper.loghelper import noLOG 

8 

9 

10def record_speech(RECORD_SECONDS=5, CHUNK=1024, FORMAT=None, 

11 CHANNELS=2, RATE=44100, 

12 WAVE_OUTPUT_FILENAME=None, fLOG=noLOG): 

13 """ 

14 Records 5 seconds by default and returns the bytes which 

15 contains that sound. 

16 

17 @param RECORD_SECONDS number of seconds to record 

18 @param WAVE_OUTPUT_FILENAME if not None, also saves the result as a filename 

19 @return bytes 

20 

21 See `pyaudio <http://people.csail.mit.edu/hubert/pyaudio/>`_ 

22 for the others parameters. 

23 """ 

24 import pyaudio 

25 if FORMAT is None: 

26 FORMAT = pyaudio.paInt16 

27 p = pyaudio.PyAudio() 

28 

29 stream = p.open(format=FORMAT, 

30 channels=CHANNELS, 

31 rate=RATE, 

32 input=True, 

33 frames_per_buffer=CHUNK) 

34 

35 fLOG("* recording") 

36 

37 frames = [] 

38 

39 for _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)): 

40 data = stream.read(CHUNK) 

41 frames.append(data) 

42 

43 fLOG("* done recording") 

44 

45 stream.stop_stream() 

46 stream.close() 

47 p.terminate() 

48 

49 if WAVE_OUTPUT_FILENAME is not None: 

50 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') 

51 wf.setnchannels(CHANNELS) 

52 wf.setsampwidth(p.get_sample_size(FORMAT)) 

53 wf.setframerate(RATE) 

54 wf.writeframes(b''.join(frames)) 

55 wf.close() 

56 

57 st = io.BytesIO() 

58 wf = wave.open(st, 'wb') 

59 wf.setnchannels(CHANNELS) 

60 wf.setsampwidth(p.get_sample_size(FORMAT)) 

61 wf.setframerate(RATE) 

62 wf.writeframes(b''.join(frames)) 

63 wf.close() 

64 return st.getvalue() 

65 

66 

67def play_speech(filename_or_bytes, CHUNK=1024): 

68 """ 

69 Play a way 

70 

71 @param filename_or_bytes wav file or bytes 

72 

73 See `pyaudio <http://people.csail.mit.edu/hubert/pyaudio/>`_ 

74 for the others parameters. 

75 """ 

76 

77 if isinstance(filename_or_bytes, str): 

78 wf = wave.open(filename_or_bytes, 'rb') 

79 else: 

80 st = io.BytesIO(filename_or_bytes) 

81 wf = wave.open(st, 'rb') 

82 

83 import pyaudio 

84 p = pyaudio.PyAudio() 

85 

86 stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), 

87 channels=wf.getnchannels(), 

88 rate=wf.getframerate(), 

89 output=True) 

90 

91 data = wf.readframes(CHUNK) 

92 

93 while len(data) > 0: 

94 stream.write(data) 

95 data = wf.readframes(CHUNK) 

96 

97 stream.stop_stream() 

98 stream.close() 

99 

100 p.terminate()