Permission to write on SD card android

前端 未结 4 666
逝去的感伤
逝去的感伤 2020-12-30 16:49

I have a problem writing to the SD card, here is the code: (Sorry about the layout of the code, just copy pased it )

public class SaveAndReadManager {

 priv         


        
4条回答
  •  粉色の甜心
    2020-12-30 17:01

    I use the following code to record audio data (successfully) to my Android's SD Card. My application requires the RECORD_AUDIO permission, but nothing else.

    File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + FILE_NAME);
    
    if (file.exists())
        file.delete();                                                          //  Delete any previous recording
    
    try
    {
        file.createNewFile();                                                   //  Create the new file
    }
    catch (IOException e)
    {
        Log.e (TAG, "Failed to create " + file.toString());
    }
    
    try
    {
        OutputStream            os  = new FileOutputStream      (file);
        BufferedOutputStream    bos = new BufferedOutputStream  (os, 8000);
        DataOutputStream        dos = new DataOutputStream      (bos);          //  Create a DataOutputStream to write the audio data to the file
    
        // Create an AudioRecord object to record the audio
        int          bufferSize     = AudioRecord.getMinBufferSize (frequency, channelConfig, Encoding);
        AudioRecord  audioRecord    = new AudioRecord (MediaRecorder.AudioSource.MIC, frequency, channelConfig, Encoding, bufferSize);
    
        short[] buffer = new short[bufferSize];                                 //  Using "short", because we're using "ENCODING_PCM_16BIT"    
        audioRecord.startRecording();
    
        while (isRecording)
        {
            int bufferReadResult = audioRecord.read (buffer, 0, bufferSize);
            for (int i = 0; i < bufferReadResult; i++)
                dos.writeShort (buffer[i]);
        }
    
        audioRecord.stop();
        dos.close();
    }
    catch (Exception t)
    {
        Log.e (TAG, "Recording Failed");
    }
    

    It would appear to me that you're missing the getAbsolutePath() call appended to your getExternalStorageDirectory() call (which may have the same result as Marc Bernstein's hard coded solution).

提交回复
热议问题