60 lines
1.6 KiB
C++
60 lines
1.6 KiB
C++
// Copyright (c) 2023 Dominic Masters
|
|
//
|
|
// This software is released under the MIT License.
|
|
// https://opensource.org/licenses/MIT
|
|
|
|
#include "AudioGen.hpp"
|
|
|
|
using namespace Dawn;
|
|
|
|
std::vector<std::string> AudioGen::getRequiredFlags() {
|
|
return std::vector<std::string>{ "input", "output" };
|
|
}
|
|
|
|
int32_t AudioGen::start() {
|
|
// Finished with XML data, now we can write data out.
|
|
File fileOut(flags["output"] + ".audio");
|
|
if(fileOut.exists()) return 0;
|
|
|
|
// Load input file
|
|
AudioFile<double> audioFile;
|
|
if(!audioFile.load(flags["input"])) {
|
|
printf("Failed to load audio file.\n");
|
|
return 1;
|
|
}
|
|
|
|
// Open Output File
|
|
fileOut.mkdirp();
|
|
if(!fileOut.open(FILE_MODE_WRITE)) {
|
|
std::cout << "Failed to open " << fileOut.filename << " output for writing" << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
// Write Header
|
|
char buffer[FILE_BUFFER_SIZE];
|
|
sprintf(buffer, "%i|%i|%i|%i|",
|
|
audioFile.getNumChannels(),
|
|
audioFile.getSampleRate(),
|
|
audioFile.getNumSamplesPerChannel(),
|
|
audioFile.getNumSamplesPerChannel() * audioFile.getNumChannels()*(
|
|
sizeof(int16_t) / sizeof(uint8_t)
|
|
)
|
|
);
|
|
auto bufferLength = strlen(buffer);
|
|
fileOut.writeRaw(buffer, bufferLength);
|
|
|
|
// Convert Data to 16 bit audio
|
|
for (int32_t i = 0; i < audioFile.getNumSamplesPerChannel(); i++) {
|
|
for(int32_t y = 0; y < audioFile.getNumChannels(); y++) {
|
|
double sample = audioFile.samples[y][i];
|
|
sample = sample < -1 ? -1 : sample > 1 ? 1 : sample;
|
|
auto q = static_cast<int16_t> (sample * 32767.);
|
|
|
|
buffer[0] = (q >> 8) & 0xFF;
|
|
buffer[1] = q & 0xFF;
|
|
fileOut.writeRaw(buffer, 2);
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
} |