Skip to content

Commit 7f686cc

Browse files
author
litongmacos
committed
add read_mp3
1 parent 7a2daa1 commit 7f686cc

File tree

4 files changed

+4870
-11
lines changed

4 files changed

+4870
-11
lines changed

common/common.cpp

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
#include <locale>
1616
#include <codecvt>
1717
#include <sstream>
18-
18+
#define DR_MP3_IMPLEMENTATION
19+
#include "dr_libs/dr_mp3.h"
1920
#if defined(_MSC_VER)
2021
#pragma warning(disable: 4244 4267) // possible loss of data
2122
#endif
@@ -713,9 +714,35 @@ read_wav(const std::string &fname, std::vector<float> &pcmf32, std::vector<std::
713714
return true;
714715
}
715716

716-
bool
717-
read_mp3(const std::string &fname, std::vector<float> &pcmf32, std::vector<std::vector<float>> &pcmf32s, bool stereo) {
717+
bool read_mp3(const std::string &fname, std::vector<float> &pcmf32, bool stereo) {
718+
drmp3 mp3;
719+
if (!drmp3_init_file(&mp3, fname.c_str(), nullptr)) {
720+
fprintf(stderr, "error: failed to open '%s' as MP3 file\n", fname.c_str());
721+
return false;
722+
}
723+
724+
if (mp3.sampleRate != COMMON_SAMPLE_RATE) {
725+
fprintf(stderr, "%s: MP3 file '%s' must be %i kHz\n", __func__, fname.c_str(), COMMON_SAMPLE_RATE / 1000);
726+
return false;
727+
}
728+
729+
if (mp3.channels != 1 && mp3.channels != 2) {
730+
fprintf(stderr, "%s: MP3 file '%s' must be mono or stereo\n", __func__, fname.c_str());
731+
return false;
732+
}
733+
734+
if (stereo && mp3.channels != 2) {
735+
fprintf(stderr, "%s: MP3 file '%s' must be stereo for this operation\n", __func__, fname.c_str());
736+
return false;
737+
}
738+
739+
drmp3_uint64 frameCount;
740+
float *pSampleData = drmp3__full_read_and_close_f32(&mp3, nullptr, &frameCount);
718741

742+
pcmf32.assign(pSampleData, pSampleData + frameCount * mp3.channels);
743+
drmp3_free(pSampleData, nullptr);
744+
745+
return true;
719746
}
720747

721748
bool

common/common.h

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,7 @@ bool read_wav(
143143
std::vector<float> &pcmf32,
144144
std::vector<std::vector<float>> &pcmf32s,
145145
bool stereo);
146-
bool
147-
read_mp3(const std::string &fname, std::vector<float> &pcmf32, std::vector<std::vector<float>> &pcmf32s, bool stereo);
146+
bool read_mp3(const std::string &fname, std::vector<float> &pcmf32, bool stereo);
148147
bool
149148
read_m4a(const std::string &fname, std::vector<float> &pcmf32, std::vector<std::vector<float>> &pcmf32s, bool stereo);
150149
// Write PCM data into WAV audio file

0 commit comments

Comments
 (0)