#include "stream.hpp" #include #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { // initialize the mpg123 library if (mpg123_init() != MPG123_OK) throw std::runtime_error("Error while initializing mpg123."); // create a new mpg123 handle int error; mpg123_handle* mpgHandle = mpg123_new(nullptr, &error); // open the mp3 file if (mpg123_open(mpgHandle, "./assets/Caravan Palace - Wonderland.mp3")) throw std::runtime_error("Could not open file."); // get the format of the file long rate; int channels; int encoding; mpg123_getformat(mpgHandle, &rate, &channels, &encoding); printf("rate: %ld, channels: %d, encoding: %d\n", rate, channels, encoding); // --- // initialize the PortAudio library if (Pa_Initialize() != paNoError) throw std::runtime_error("Could not initialize PortAudio."); // open the PortAudio stream PaStream* stream; if (Pa_OpenDefaultStream( &stream, 0, channels, paInt16, static_cast(rate), 512, nullptr, nullptr ) != paNoError) throw std::runtime_error("Could not open PortAudio stream."); // start the PortAudio stream if (Pa_StartStream(stream) != paNoError) throw std::runtime_error("Could not start the PortAudio stream."); // --- // read the file std::vector buffer(4096); std::size_t done; std::size_t i = 0; while ((error = mpg123_read(mpgHandle, buffer.data(), buffer.size(), &done)) == MPG123_OK) { // write the audio data to the PortAudio stream if ((error = Pa_WriteStream(stream, buffer.data(), done / 2 / channels)) != paNoError) throw std::runtime_error( "Could not write audio data in the PortAudio stream.\n" + std::string(Pa_GetErrorText(error)) ); printf("write (%04lu)\n", i++); } // display the error message std::printf(mpg123_plain_strerror(error)); // Stop the audio stream Pa_StopStream(stream); Pa_CloseStream(stream); // delete the mpg123 handle mpg123_close(mpgHandle); mpg123_delete(mpgHandle); // free the libraries Pa_Terminate(); mpg123_exit(); return error; }