19 #include <boost/filesystem.hpp>
22 #include <pv_recorder.h>
34 using namespace std::chrono;
35 unsigned long ms_since_epoch = duration_cast<milliseconds>(system_clock::now().
time_since_epoch()).count();
36 unsigned long seconds_since_epoch = ms_since_epoch / 1e3;
37 unsigned long ms_decimals_since_epoch = ms_since_epoch - seconds_since_epoch * 1e3;
38 return std::to_string(seconds_since_epoch) +
"." + std::to_string(ms_decimals_since_epoch);
41 void writeWav(
const std::vector<int16_t>& buffer,
size_t buffer_size,
size_t sample_rate,
const std::string& directory)
43 boost::filesystem::create_directories(directory);
44 std::string filename = directory +
"/recording-" +
getEpochStamp() +
".wav";
48 sfinfo.samplerate = sample_rate;
49 sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
50 SNDFILE* outfile = sf_open(filename.c_str(), SFM_WRITE, &sfinfo);
51 if (outfile !=
nullptr)
53 sf_write_short(outfile, buffer.data(), buffer_size);
54 sf_write_sync(outfile);
65 catch (
const std::exception& e)
67 throw std::runtime_error(
"recognizeInit failed: " + std::string(e.what()));
75 catch (
const std::exception& e)
77 throw std::runtime_error(
"getRecordSettings failed: " + std::string(e.what()));
84 throw std::runtime_error(
"Failed to initialize device with " +
92 throw std::runtime_error(
"Failed to start device with " +
96 bool is_finalized =
false;
97 size_t frame_index = 0;
100 std::vector<int16_t> record_buffer(record_settings.
frame_length_ * total_frames, 0);
115 catch (
const std::exception& e)
119 throw std::runtime_error(
"recognizeProcess failed: " + std::string(e.what()));
122 std::copy(pcm.begin(), pcm.end(), record_buffer.begin() + frame_index * pcm.size());
131 throw std::runtime_error(
"Failed to stop device with " +
151 catch (
const std::exception& e)
168 throw std::runtime_error(
"Recognizer not initialized");
173 throw std::runtime_error(
"Already recognizing");
185 throw std::runtime_error(
"Recognizer not initialized");
194 throw std::runtime_error(
"Recognizer not initialized");
203 throw std::runtime_error(
"Recognizer not initialized");
215 return is_recognizing;