| 132 | |
| 133 | |
| 134 | bool RecorderNode::writeRecordingToWav(const std::string & filenameWithWavExtension, bool mixToMono) |
| 135 | { |
| 136 | size_t recordedChannelCount = m_data.size(); |
| 137 | if (!recordedChannelCount) return false; |
| 138 | size_t numSamples = m_data[0].size(); |
| 139 | if (!numSamples) return false; |
| 140 | |
| 141 | std::unique_ptr<nqr::AudioData> fileData(new nqr::AudioData()); |
| 142 | |
| 143 | std::vector<std::vector<float>> clear_data; |
| 144 | for (int i = 0; i < recordedChannelCount; ++i) |
| 145 | clear_data.emplace_back(std::vector<float>()); |
| 146 | |
| 147 | { |
| 148 | std::lock_guard<std::recursive_mutex> lock(m_mutex); |
| 149 | m_data.swap(clear_data); |
| 150 | } |
| 151 | |
| 152 | if (recordedChannelCount == 1) |
| 153 | { |
| 154 | // only one channel recorded |
| 155 | fileData->samples.resize(numSamples); |
| 156 | fileData->channelCount = 1; |
| 157 | float* dst = fileData->samples.data(); |
| 158 | memcpy(dst, clear_data[0].data(), sizeof(float) * numSamples); |
| 159 | } |
| 160 | else if (recordedChannelCount > 1 && mixToMono) |
| 161 | { |
| 162 | // Mix channels to mono if requested, and there's more than one input channel. |
| 163 | fileData->samples.resize(numSamples); |
| 164 | fileData->channelCount = 1; |
| 165 | float* dst = fileData->samples.data(); |
| 166 | for (size_t i = 0; i < numSamples; i++) |
| 167 | { |
| 168 | dst[i] = 0; |
| 169 | for (size_t j = 0; j < m_channelCount; ++j) |
| 170 | dst[i] += clear_data[j][i]; |
| 171 | dst[i] *= 1.f / static_cast<float>(m_channelCount); |
| 172 | } |
| 173 | } |
| 174 | else |
| 175 | { |
| 176 | // straight through |
| 177 | fileData->samples.resize(numSamples * recordedChannelCount); |
| 178 | fileData->channelCount = static_cast<int>(recordedChannelCount); |
| 179 | float* dst = fileData->samples.data(); |
| 180 | for (size_t i = 0; i < numSamples; i++) |
| 181 | { |
| 182 | for (size_t j = 0; j < recordedChannelCount; ++j) |
| 183 | *dst++ = clear_data[j][i]; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | fileData->sampleRate = static_cast<int>(m_sampleRate); |
| 188 | fileData->sourceFormat = nqr::PCM_FLT; |
| 189 | |
| 190 | nqr::EncoderParams params = {static_cast<int>(recordedChannelCount), nqr::PCM_FLT, nqr::DITHER_NONE}; |
| 191 | bool result = nqr::EncoderError::NoError == nqr::encode_wav_to_disk(params, fileData.get(), filenameWithWavExtension); |