Skip to content

Recording audio

Recording audio with the microphone of TIAGo Pro can be done from native ubuntu tools and using ROS 2. Namely, subscribing to the /audio_in/raw and then saving the audio data to a .wav file.

This tutorial guides you through this process by writing a simple ROS 2 node in Python.

Step 1: Write a script to record the audio

The following code is the implementation of a ROS 2 node that captures audio. Create a file named audio_record.py with the following content:

import wave
import rclpy
from rclpy.node import Node
from audio_common_msgs.msg import AudioData

AUDIO_RATE = 16000
AUDIO_CHANNELS = 1
AUDIO_WIDTH = 2

class AudioRecorder(Node):
    def __init__(self):
        super().__init__('record_audio')
        self.wf = wave.open("test_audio.wav", 'wb')  # Change output directory as desired
        self.wf.setnchannels(AUDIO_CHANNELS)
        self.wf.setsampwidth(AUDIO_WIDTH)
        self.wf.setframerate(AUDIO_RATE)

        self.subscription = self.create_subscription(
            AudioData,
            '/audio_in/raw',
            self.channel_callback,
            10)
        self.get_logger().info("Recording...")

    def channel_callback(self, msg):
        self.wf.writeframes(msg.data)

    def close_file(self):
        self.get_logger().info("Saving...")
        self.wf.close()


def main(args=None):
    rclpy.init(args=args)
    recorder = AudioRecorder()

    try:
        rclpy.spin(recorder)
    except KeyboardInterrupt:
        recorder.get_logger().info("Stopping recording...")
    finally:
        recorder.close_file()
        recorder.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()

Step 2: Execute the script

To execute the script, call the Python interpreter:

python3 audio_record.py

If you were running the script on a remote machine (e.g., a laptop) you would need connection to the robot.

Press CTRL+C to stop the recording.

Step 3: Playback and transfer

The recorded file is saved in the directory where the command was executed. To play the file locally, do

aplay test_audio.wav

If the recording was performed directly on the robot, the file can be transferred to a local machine using scp:

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