../_images/tiagopro-icon.png ../_images/tiago-head-icon.png ../_images/tiago-icon.png ../_images/ari-icon.png

Recording audio with ROS and Python#

🏁 Goal of this tutorial

Write a Python script that subscribes to the /audio_in/raw topic and writes it to a .wav file.

On your development machine, or directly on your robot, create a new Python script audio_record.py with the following content:

audio_record.py#
 1import wave
 2import rclpy
 3from rclpy.node import Node
 4from audio_common_msgs.msg import AudioData
 5
 6AUDIO_RATE = 16000
 7AUDIO_CHANNELS = 1
 8AUDIO_WIDTH = 2
 9
10class AudioRecorder(Node):
11    def __init__(self):
12        super().__init__('record_audio')
13        self.wf = wave.open("test_audio.wav", 'wb')  # Change output directory as desired
14        self.wf.setnchannels(AUDIO_CHANNELS)
15        self.wf.setsampwidth(AUDIO_WIDTH)
16        self.wf.setframerate(AUDIO_RATE)
17
18        self.subscription = self.create_subscription(
19            AudioData,
20            '/audio_in/raw',
21            self.channel_callback,
22            10)
23        self.get_logger().info("Recording...")
24
25    def channel_callback(self, msg):
26        self.wf.writeframes(msg.data)
27
28    def close_file(self):
29        self.get_logger().info("Saving...")
30        self.wf.close()
31
32
33def main(args=None):
34    rclpy.init(args=args)
35    recorder = AudioRecorder()
36
37    try:
38        rclpy.spin(recorder)
39    except KeyboardInterrupt:
40        recorder.get_logger().info("Stopping recording...")
41    finally:
42        recorder.close_file()
43        recorder.destroy_node()
44        rclpy.shutdown()
45
46
47if __name__ == '__main__':
48    main()

To run it, simply call the Python interpreter with the script:

python3 audio_record.py

Important

If you are running this script on your laptop, you need to have a working connection to your robot. Please carefully follow the instructions in Set up ROS 2 communication with the robot.

Speak to the robot, and press CTRL+C to stop the recording.

You can then play the recorded file (note the file is saved from wherever you have executed the recording command):

aplay test_audio.wav

If you have recorded it from the robot, you can then copy it back to your laptop. From your laptop directory:

scp pal@<robot>-0c:/home/pal/test_audio.wav ~/desired_dir_on_my_laptop

See also#