I'm trying to create my own MP3 audio file. How would I go about doing this?
File mySong = new File("generated song.mp3");
FileOutputStream song = new FileOutputStream(mySong);
for (int n = 0; n < 3000; n++){
song.write(n % 256);
}
song.close();
I tried the above code, but Windows gave me an error when I tried playing it back. I imagine there must be some beginning and ending sequence of bytes that I need to write to the file in order for it to be properly decoded. So, how could I generate my own .MP3 file?
Before I answer your question, let me explain some key concepts of digital audio and MP3.
MP3 is a compressed digital audio file. Digital audio, in a raw form, consists of audio 'samples'. A typical 44.1 kHz mono (single channel) raw audio will have 44100 audio samples, each of size 16-bits. If it is a stereo, then there will 44100 x 2 samples, each of size 16-bits. Note that a 5-minute raw audio file would be 50MB in size.
MP3 is compressed audio. It employs complex compression algorithm to reduce the size of the audio. Hence you cannot write the way you would write a raw audio file.
There are two ways of creating your own MP3 file.
(1) Create a raw WAV file and then encode it as MP3 using a compression library. You can take a look at this answer Is there any pure java way to convert .wav to .mp3?
(2) Use an MP3 compression library that accepts raw samples.
Hope that helps.