Search code examples
androidaudioaudio-recordingandroid-mediarecorder

Store multiple audio files in single directory- Android


I am trying to build an android audio recorder app, where the audio recordings should be stored in a directory within my phone internal storage.

This is my code in Android Studio:

File  AudioDir=new File("/sdcard/Audiofiles/");
AudioDir.mkdir();
String filename="recording.mp3";
output  = new File(AudioDir.getAbsolutePath(), filename);
output.createNewFile();

This code stores a single audio file in Audiofiles folder and overwrites the new audio recording.
I am getting the latest recording with the name recording.mp3. The old ones are gone.

I want multiple recordings to be stored within the same directory. I tried coding it, but could not find any success. Please help.

This is the code I wrote :

   AudioDir=new File("/sdcard/Audiofiles/");
   AudioDir.mkdir();
   File output=null;

   Boolean flag=false;
   String filename=null;
   File file[]=AudioDir.listFiles();

       for(int i=0;i<file.length;i++)
       {
           if (file[i].equals(filename))
              flag=true;
           else
              flag=false;
       }

       if(flag==true)
       {
           System.out.println(i +" :flag==true");
           filename="recording"+i+".mp3";
           output  = new File(AudioDir.getAbsolutePath(), filename);
           output.createNewFile();

       }
       else if(flag==false)
       {
           System.out.println(i +" :flag==false");
           filename="recording"+i+".mp3";
           output  = new File(AudioDir.getAbsolutePath(), filename);
           output.createNewFile();
           i++;

       }

Now, what happens is that, I get files with unique names in the folder.. Cool..!! But, once i close the app, and open it again and record the audio, the previous files get overwrites.. I don't want that to happen. I need all the files.. What should I do ??


Solution

  • Your files are overwritten because they have the same name. You must provide a different name for each one you save, for example "recording" + a timestamp + ".mp3".