File: sound_capture.py

package info (click to toggle)
python-sfml 1.5.1.is.1.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,456 kB
  • ctags: 1,585
  • sloc: python: 5,747; cpp: 285; makefile: 147
file content (72 lines) | stat: -rw-r--r-- 2,115 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pySFML - Python bindings for SFML
# Copyright 2012-2013, Jonathan De Wachter <dewachter.jonathan@gmail.com>
#
# This software is released under the LGPLv3 license.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import sfml as sf

# python 2.* compatability
try: input = raw_input
except NameError: pass

def main():
	# check that the device can capture audio
	if not sf.SoundRecorder.is_available():
		print("Sorry, audio capture is not supported by your system")
		return

	# choose the sample rate
	sample_rate = int(input("Please choose the sample rate for sound capture (44100 is CD quality): "))

	# wait for user input...
	input("Press enter to start recording audio")

	# here we'll use an integrated custom recorder, which saves the captured data into a sf.SoundBuffer
	recorder = sf.SoundBufferRecorder()

	# audio capture is done in a separate thread, so we can block the main thread while it is capturing
	recorder.start(sample_rate)
	input("Recording... press enter to stop")
	recorder.stop()

	# get the buffer containing the captured data
	buffer = recorder.buffer

	# display captured sound informations
	print("Sound information:")
	print("{0} seconds".format(buffer.duration))
	print("{0} samples / seconds".format(buffer.sample_rate))
	print("{0} channels".format(buffer.channel_count))

	# choose what to do with the recorded sound data
	choice = input("What do you want to do with captured sound (p = play, s = save) ? ")

	if choice == 's':
		# choose the filename
		filename = input("Choose the file to create: ")

		# save the buffer
		buffer.to_file(filename);
	else:
		# create a sound instance and play it
		sound = sf.Sound(buffer)
		sound.play();

		# wait until finished
		while sound.status == sf.Sound.PLAYING:
			# leave some CPU time for other threads
			sf.sleep(sf.milliseconds(100))

	# finished !
	print("Done !")

	# wait until the user presses 'enter' key
	input("Press enter to exit...")

if __name__ == "__main__":
	main()