audio_common for ROS 2
Loading...
Searching...
No Matches
wave_file.hpp
Go to the documentation of this file.
1// MIT License
2//
3// Copyright (c) 2024 Miguel Ángel González Santamarta
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23#ifndef AUDIO_COMMON__WAVE_FILE_HPP
24#define AUDIO_COMMON__WAVE_FILE_HPP
25
26#include <fstream>
27#include <string>
28#include <vector>
29
30namespace audio_common {
31
32class WaveFile {
33public:
34 explicit WaveFile(const std::string &filepath);
35 ~WaveFile();
36
37 bool open();
38 void rewind();
39 bool read(std::vector<float> &buffer, size_t size);
40 int get_sample_rate() const { return this->sample_rate_; }
41 int get_num_channels() const { return this->channels_; }
42 int get_bits_per_sample() const { return this->bits_per_sample_; }
43
44private:
45 std::string filepath_;
46 std::ifstream file_;
50
51 // Convert int16_t sample to float [-1.0, 1.0]
52 float int16ToFloat(int16_t sample) { return sample / 32768.0f; }
53};
54
55} // namespace audio_common
56
57#endif // WAVE_FILE_HPP
float int16ToFloat(int16_t sample)
Definition wave_file.hpp:52
int get_num_channels() const
Definition wave_file.hpp:41
bool read(std::vector< float > &buffer, size_t size)
Definition wave_file.cpp:63
WaveFile(const std::string &filepath)
Definition wave_file.cpp:30
int sample_rate_
Definition wave_file.hpp:47
int get_sample_rate() const
Definition wave_file.hpp:40
int bits_per_sample_
Definition wave_file.hpp:49
bool open()
Definition wave_file.cpp:35
int channels_
Definition wave_file.hpp:48
int get_bits_per_sample() const
Definition wave_file.hpp:42
void rewind()
Definition wave_file.cpp:58
~WaveFile()
Definition wave_file.cpp:33
std::string filepath_
Definition wave_file.hpp:45
std::ifstream file_
Definition wave_file.hpp:46
Definition audio_capturer_node.hpp:32