| 1 | /* |
| 2 | Copyright 2018 Google Inc. All Rights Reserved. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS-IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "utils/wav.h" |
| 18 | |
| 19 | #include <cerrno> |
| 20 | #include <fstream> |
| 21 | #include <string> |
| 22 | |
| 23 | #include "base/integral_types.h" |
| 24 | #include "base/logging.h" |
| 25 | #include "utils/wav_reader.h" |
| 26 | |
| 27 | namespace vraudio { |
| 28 | |
| 29 | Wav::Wav(size_t num_channels, int sample_rate, |
| 30 | std::vector<int16_t>&& interleaved_samples) |
| 31 | : num_channels_(num_channels), |
| 32 | sample_rate_(sample_rate), |
| 33 | interleaved_samples_(interleaved_samples) {} |
| 34 | |
| 35 | Wav::~Wav() {} |
| 36 | |
| 37 | std::unique_ptr<const Wav> Wav::CreateOrNull(std::istream* binary_stream) { |
| 38 | WavReader wav_reader(binary_stream); |
| 39 | const size_t num_total_samples = wav_reader.GetNumTotalSamples(); |
| 40 | if (!wav_reader.IsHeaderValid() || num_total_samples == 0) { |
| 41 | return nullptr; |
| 42 | } |
| 43 | std::vector<int16> interleaved_samples(num_total_samples); |
| 44 | if (wav_reader.ReadSamples(num_samples: num_total_samples, target_buffer: &interleaved_samples[0]) != |
| 45 | num_total_samples) { |
| 46 | return nullptr; |
| 47 | } |
| 48 | return std::unique_ptr<Wav>(new Wav(wav_reader.GetNumChannels(), |
| 49 | wav_reader.GetSampleRateHz(), |
| 50 | std::move(interleaved_samples))); |
| 51 | } |
| 52 | |
| 53 | } // namespace vraudio |
| 54 | |