YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
yarpAudioPlayer.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2024 Istituto Italiano di Tecnologia (IIT)
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5
6#include <yarp/os/all.h>
7#include <yarp/sig/Sound.h>
10#include <cmath>
11#include "yarpAudioPlayer_IDL.h"
12
13using namespace yarp::os;
14using namespace yarp::sig;
15
16
17// ******************** THE MODULE ********************
19{
20 protected:
21 std::string m_name = "/yarpAudioPlayer";
25 size_t m_split_size = 16000;
26
27 public: //yarpAudioPlayer_IDL methods
28 bool play(const std::string& filename) override;
29 bool test(const std::string& type, const double duration, const double frequency,const std::int16_t amplitude, const std::int16_t sampling_rate, const std::int16_t channels) override;
30
31 protected: //internal methods
32 bool openFile(const std::string& file_name);
33 bool send();
34
35 protected: // RFModule methods
37 {
38 bool ret;
39 std::string test_string = rf.toString();
40
41 // generic configuration
42 if (rf.check("name"))
43 { m_name = std::string("/") + rf.find("name").asString().c_str(); }
44
45 if (rf.check("split_size"))
46 { m_split_size = rf.find("split_size").asInt32(); }
47
48 if (rf.check("help"))
49 {
50 yInfo() << "yarpAudioPlayer --name <portname> --split_size <value>";
51 yInfo() << "portname: prefix for the opened ports default: /yarpAudioPlayer";
52 yInfo() << "value: int32 (default value 16000) The output sound will be split into packets of <value> samples each";
53 yInfo() << "the tool accepts commands on its rpc port";
54 yInfo() << "";
55 return false;
56 }
57
58 // rpc port
59 ret = m_rpcPort.open((m_name + "/rpc").c_str());
60 if (!ret) { return false;}
61
62 this->yarp().attachAsServer(m_rpcPort);
63
64 // output audio port
65 ret = m_audioPort.open(m_name + "/audio:o");
66 if (!ret) { return false;}
67
68 yInfo() << "Module started. Send commands to the RPC port" << m_name + "/rpc" << " to play audio files.";
69
70 return true;
71 }
72
73 bool close() override
74 {
77 return true;
78 }
79
80 virtual double getPeriod() override
81 {
82 return 1.0;
83 }
84
85 bool updateModule() override
86 {
87 return true;
88 }
89};
90
91// ******************** Main ********************
92
93int main(int argc, char *argv[])
94{
96 rf.setDefaultContext("yarpAudioPlayer");
97 rf.configure(argc,argv);
98
100
101 if (!yarp.checkNetwork())
102 {
103 yError() << "yarp.checkNetwork() failed.";
104 return -1;
105 }
106
107 PlayerModule mod;
108
109 return mod.runModule(rf);
110}
111
112// ******************** Methods implementation ********************
113
114bool PlayerModule::play(const std::string& filename)
115{
116 bool ret;
117 ret = openFile(filename);
118 if (!ret) { return false; }
119
120 ret = send();
121 if (!ret) { return false; }
122 return true;
123}
124
125bool PlayerModule::test(const std::string& type, const double duration, const double frequency,const std::int16_t amplitude, const std::int16_t sampling_rate, const std::int16_t channels)
126{
127 bool ret;
128 if (type == "sine")
129 { ret = yarp::sig::utils::makeTone(m_audioFile,duration,channels, sampling_rate, frequency, amplitude); }
130 else if (type == "sawtooth" )
131 { ret = yarp::sig::utils::makeSawTooth(m_audioFile,duration,channels,sampling_rate, frequency, amplitude); }
132 else if (type == "squarewave" )
133 { ret = yarp::sig::utils::makeSquareWave(m_audioFile,duration,channels,sampling_rate, frequency, amplitude); }
134 else
135 {
136 yInfo() << "Invalid type, should be `sine`, `sawtooth`, or `squarewave`";
137 return false;
138 }
139
140 yInfo() << "Generated tone of " << duration << "s, with the following properties: samples:" << m_audioFile.getSamples() << " channels:"<< m_audioFile.getChannels() << " frequency:" << m_audioFile.getFrequency() << " bytes per samples:" << m_audioFile.getBytesPerSample();
141 if (!ret) { return false; }
142
143 ret = send();
144 if (!ret) { return false; }
145 return true;
146}
147
148bool PlayerModule::openFile(const std::string& file_name)
149{
150 yInfo() << "Opening file:" << file_name;
151 double st= yarp::os::Time::now();
152 //reset completely the sound (frequency, channels, etc)
154 //load the audio file
155 bool ret = yarp::sig::file::read(m_audioFile, file_name.c_str());
156 double en= yarp::os::Time::now();
157
158 if (ret == false)
159 {
160 yError() << "Unable to open file" << file_name.c_str();
161 return false;
162 }
163 yInfo() << "File loaded in: " << en - st << "s";
164 yInfo() << "Loaded file has the following properties: samples:" << m_audioFile.getSamples() << " channels:"<< m_audioFile.getChannels() << " frequency:" << m_audioFile.getFrequency() << " bytes per samples:" << m_audioFile.getBytesPerSample();
165 return true;
166}
167
169{
170 bool ret;
171 double st= yarp::os::Time::now();
172 yInfo() << "Sending sound...";
173 if (m_audioPort.getOutputCount() > 0)
174 {
175 if (m_split_size==0)
176 {
177 //send the whole file
179 }
180 else
181 {
182 //split the file in blocks of fixed size
184
185 //this is a ceiling division on integers so that: 10 / 3 = 4
186 size_t iterations = (totalSamples + m_split_size - 1) / m_split_size;
187
188 size_t block_counter =0;
189 for (size_t first = 0; first < totalSamples; first += m_split_size)
190 {
191 Sound block = m_audioFile.subSound(first, m_split_size);
192 double st_block = yarp::os::Time::now();
193 ret = m_audioPort.write(block);
194 double en_block = yarp::os::Time::now();
195 yInfo() << "Sent block" << block_counter << "/" << iterations << " with " << block.getSamples() << " samples in" << en_block - st_block << "s";
197 }
198 }
199 }
200 else
201 {
202 yWarning() << "No receivers are connected";
203 }
204 double en= yarp::os::Time::now();
205 yInfo() << "Sound sent in: " << en - st << "s";
206
207 return true;
208}
#define yInfo(...)
Definition Log.h:319
#define yError(...)
Definition Log.h:361
#define yWarning(...)
Definition Log.h:340
bool openFile(const std::string &file_name)
bool updateModule() override
Override this to do whatever your module needs to do.
bool configure(yarp::os::ResourceFinder &rf) override
Configure the module, pass a ResourceFinder object to the module.
bool close() override
Close function.
yarp::os::Port m_rpcPort
yarp::os::Port m_audioPort
yarp::sig::Sound m_audioFile
virtual double getPeriod() override
You can override this to control the approximate periodicity at which updateModule() is called by run...
std::string m_name
bool test(const std::string &type, const double duration, const double frequency, const std::int16_t amplitude, const std::int16_t sampling_rate, const std::int16_t channels) override
Generate and send a test sound.
bool play(const std::string &filename) override
Play the given audio file.
yarpAudioPlayer_IDL Interface.
A mini-server for performing network communication in the background.
Utilities for manipulating the YARP network, including initialization and shutdown.
Definition Network.h:718
A mini-server for network communication.
Definition Port.h:46
int getOutputCount() override
Determine how many output connections this port has.
Definition Port.cpp:526
bool write(const PortWriter &writer, const PortWriter *callback=nullptr) const override
Write an object to the port.
Definition Port.cpp:395
void close() override
Stop port activity.
Definition Port.cpp:330
bool open(const std::string &name) override
Start port operation, with a specific name, with automatically-chosen network parameters.
Definition Port.cpp:79
A base-class for standard YARP modules that supports ResourceFinder.
Definition RFModule.h:20
virtual int runModule()
Calls updateModule() until that returns false.
Definition RFModule.cpp:323
Helper class for finding config files and other external resources.
bool check(const std::string &key) const override
Check if there exists a property of the given name.
bool setDefaultContext(const std::string &contextName)
Sets the context for the current ResourceFinder object.
bool configure(int argc, char *argv[], bool skipFirstArgument=true)
Sets up the ResourceFinder.
std::string toString() const override
Return a standard text representation of the content of the object.
Value & find(const std::string &key) const override
Gets a value corresponding to a given keyword.
virtual std::int32_t asInt32() const
Get 32-bit integer value.
Definition Value.cpp:210
virtual std::string asString() const
Get string value.
Definition Value.cpp:246
yarp::os::WireLink & yarp()
Get YARP state associated with this object.
Definition Wire.h:28
Class for storing sounds See Audio in YARP for additional documentation on YARP audio.
Definition Sound.h:42
Sound subSound(size_t first_sample, size_t len)
Returns a subpart of the sound.
Definition Sound.cpp:186
size_t getBytesPerSample() const
Get the number of bytes per sample.
Definition Sound.cpp:659
size_t getChannels() const
Get the number of channels of the sound.
Definition Sound.cpp:669
int getFrequency() const
Get the frequency of the sound (i.e.
Definition Sound.cpp:364
size_t getSamples() const
Get the number of samples contained in the sound.
Definition Sound.cpp:664
double now()
Return the current time in seconds, relative to an arbitrary starting point.
Definition Time.cpp:121
An interface to the operating system, including Port based communication.
Definition OSTestMsg.cpp:13
bool read(ImageOf< PixelRgb > &dest, const std::string &src, image_fileformat format=FORMAT_ANY)
bool makeSawTooth(Sound &outSound, double duration_s=1.0, size_t channels=1, size_t sampleRate=16000, double frequency=1, size_t amplitude=30000)
Generate a sound containing a sawtooth signal.
bool makeTone(Sound &outSound, double duration_s=1.0, size_t channels=1, size_t sampleRate=16000, double frequency=440, size_t amplitude=30000)
Generate a sound containing a sine wave tone.
bool makeSquareWave(Sound &outSound, double duration_s=1.0, size_t channels=1, size_t sampleRate=16000, double frequency=1, size_t amplitude=30000)
Generate a sound containing a square wave signal.
The main, catch-all namespace for YARP.
Definition dirs.h:16
int main(int argc, char *argv[])