Search code examples
androidaudiomedia-playersoundpool

Record and playback a sound on Android without storing a temporary file


In my app I want to record a 2-second long sound and play it back to the user. All examples I've found so far require that the audio data for playback either comes from a file or from a URL.

Both MediaPlayer and SoundPool classes accept only files, file descriptors, resource id's or URLs as input and not just, say, a byte array.

Since one can only write files to the SD card and NOT internal storage (is this so?), the app would require that an SD card is mounted and writable. But my app should also work if no SD card is present.

Is there a way to achieve this? Thanks


Solution

  • Yes, an App can write to internal storage (where it is installed). Every Installed app is provided a Data folder to write its internal files. Also there is a cache storage provided.

    These methods of Context can get you these directories:

    • getCacheDir() : Returns the absolute path to the application specific cache directory on the filesystem (Note: System may delete cache if its low on storage)

    • getDir(String name, int mode) : Retrieve, creating if needed, a new directory in which the application can place its own custom data files.

    Also there is a method for External storage: getExternalCacheDir() but is unreliable since external storage might not be always there.

    Also, if you just need to write files in App's internal data directory, there is a very simple method:

    openFileOutput (String name, int mode)