I have a short code that streams the recorded audio in realtime to the speakers if the user push the start button. After he pushes the stop button, the buffered audio should be saved in a mp3 file. The file was created but it is empty. If I try to play the file I cant hear anything.
public class MainActivity extends Activity {
boolean m_stop = true;
AudioTrack m_audioTrack;
Thread m_noiseThread;
static final int bufferSize = 200000;
AudioRecord arec;
FileOutputStream os = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onStartStopClicked(View v)
{
Button StartButton = (Button)findViewById(R.id.StartStop);
if(m_stop) {
start();
} else {
stop();
}
}
Runnable m_noiseGenerator = new Runnable()
{
public void run()
{
String filepath = Environment.getExternalStorageDirectory().toString();
os = new FileOutputStream(filepath + "/test.mp3");
int buffersize1 = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize1);
m_audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 8000, AudioTrack.MODE_STREAM);
byte[] buffer = new byte[buffersize1];
arec.startRecording();
m_audioTrack.play();
while(!m_stop)
{
arec.read(buffer, 0, buffersize1);
m_audioTrack.write(buffer, 0, buffer.length);
os.write(buffer);
}
}
};
public void start()
{
m_stop = false;
m_noiseThread = new Thread(m_noiseGenerator);
m_noiseThread.start();
}
public void stop()
{
m_stop = true;
arec.stop();
m_audioTrack.stop();
os.flush();
os.close();
}
}
Can someone help me to fix that? That would be great thanks :)