| 30 | }; |
| 31 | |
| 32 | class Wav : BigEndian<true> { |
| 33 | // Little-endian versions of text values |
| 34 | uint32_t value_RIFF = 0x46464952; |
| 35 | uint32_t value_WAVE = 0x45564157; |
| 36 | uint32_t value_fmt = 0x20746d66; |
| 37 | uint32_t value_data = 0x61746164; |
| 38 | |
| 39 | using BigEndian<true>::read16; |
| 40 | using BigEndian<true>::read32; |
| 41 | using BigEndian<true>::write16; |
| 42 | using BigEndian<true>::write32; |
| 43 | |
| 44 | public: |
| 45 | struct Result { |
| 46 | enum class Code { |
| 47 | OK = 0, |
| 48 | IO_ERROR, |
| 49 | FORMAT_ERROR, |
| 50 | UNSUPPORTED, |
| 51 | WEIRD_CONFIG |
| 52 | }; |
| 53 | Code code = Code::OK; |
| 54 | std::string reason; |
| 55 | |
| 56 | Result(Code code, std::string reason="") : code(code), reason(reason) {}; |
| 57 | Result(const Result &other) : code(other.code), reason(other.reason) {}; |
| 58 | Result & operator=(const Result &other) { |
| 59 | // TODO: what is this? Why do we only copy if it's _not_ OK? |
| 60 | if (code == Code::OK) { |
| 61 | code = other.code; |
| 62 | reason = other.reason; |
| 63 | } |
| 64 | return *this; |
| 65 | } |
| 66 | // Used to neatly test for success |
| 67 | explicit operator bool () const { |
| 68 | return code == Code::OK; |
| 69 | }; |
| 70 | const Result & warn(std::ostream& output=std::cerr) const { |
| 71 | if (!(bool)*this) { |
| 72 | output << "WAV error: " << reason << std::endl; |
| 73 | } |
| 74 | return *this; |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | unsigned int sampleRate = 48000; |
| 79 | unsigned int channels = 1; |
| 80 | std::vector<double> samples; |
| 81 | Result result = Result(Result::Code::OK); |
| 82 | |
| 83 | Wav() {} |
| 84 | Wav(double sampleRate, int channels) : sampleRate(sampleRate), channels(channels) {} |
| 85 | Wav(double sampleRate, int channels, const std::vector<double> &samples) : sampleRate(sampleRate), channels(channels), samples(samples) {} |
| 86 | Wav(std::string filename) { |
| 87 | result = read(filename).warn(); |
| 88 | } |
| 89 | |