audio.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #pragma once
  2. #include <vector>
  3. #include <string>
  4. #include <stdexcept>
  5. /**
  6. * Audio buffer structure for storing audio data.
  7. * Data is stored in interleaved format (L, R, L, R, ...) for stereo.
  8. */
  9. struct AudioBuffer {
  10. std::vector<float> data; // Interleaved samples
  11. unsigned int channels;
  12. unsigned int sampleRate;
  13. size_t samples; // Total samples (frames * channels)
  14. };
  15. /**
  16. * Audio file I/O utilities.
  17. * Supports any common audio format (WAV, MP3, FLAC, OGG, etc.) via FFmpeg/libav.
  18. * Automatically resamples to target sample rate if needed.
  19. */
  20. class AudioFile {
  21. public:
  22. /**
  23. * Load audio from any common audio file format.
  24. * Audio is automatically resampled to 44100 Hz and converted to stereo float32.
  25. * @param path Path to the audio file
  26. * @param target_sample_rate Target sample rate (default: 44100 Hz)
  27. * @return AudioBuffer containing the loaded audio data
  28. * @throws std::runtime_error if the file cannot be opened or decoded
  29. */
  30. static AudioBuffer Load(const std::string& path, int target_sample_rate = 44100);
  31. /**
  32. * Save audio to a WAV file (PCM float32).
  33. * @param path Path to save the WAV file
  34. * @param buffer AudioBuffer containing audio data to save
  35. * @throws std::runtime_error if the file cannot be written
  36. */
  37. static void Save(const std::string& path, const AudioBuffer& buffer);
  38. };