title: Android Base64 Audio File Encode and Decode
body: <p><strong>What I am doing:</strong>  I am currently recording voice and saving it as a file in SDCard which is running / playing fine in MediaPlayer.</p>
  
  <p><strong>What I want:</strong> When I encode this file intoBase64 and send to server, everything goes fine. But When i decode the Base64 String into audio.m4a file, it is not running in MediaPlayer.  </p>
  
  <p>I had tried <strong>.m4a</strong> , <strong>.wav</strong> but all in vain.<br>
  The problem is in encoding. Because when I decode a file sent from the same iOS app, it runs fine in MediaPlayer.  </p>
  
  <p>I know its very basic and alot of help is there to encode decode but nothing is working. Following is my approach:</p>
  
  <pre><code> private void encodeAudio(String selectedPath) {
  
      byte[] audioBytes;
      try {
  
          // Just to check file size.. Its is correct i-e; Not Zero
          File audioFile = new File(selectedPath);
          long fileSize = audioFile.length();
  
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          FileInputStream fis = new FileInputStream(new File(selectedPath));
          byte[] buf = new byte[1024];
          int n;
          while (-1 != (n = fis.read(buf)))
              baos.write(buf, 0, n);
          audioBytes = baos.toByteArray();
  
          // Here goes the Base64 string
          _audioBase64 = Base64.encodeToString(audioBytes, Base64.DEFAULT);
  
      } catch (Exception e) {
          DiagnosticHelper.writeException(e);
      }
  
  }  
  </code></pre>
  
  <p><strong>And Decoding in the following way:</strong>  </p>
  
  <pre><code>private void decodeAudio(String base64AudioData, File fileName, String path, MediaPlayer mp) {
  
      try {
  
          FileOutputStream fos = new FileOutputStream(fileName);
          fos.write(Base64.decode(base64AudioData.getBytes(), Base64.DEFAULT));
          fos.close();
  
          try {
  
              mp = new MediaPlayer();
              mp.setDataSource(path);
              mp.prepare();
              mp.start();
  
          } catch (Exception e) {
  
              DiagnosticHelper.writeException(e);
  
          }
  
      } catch (Exception e) {
          e.printStackTrace();
      }
  
  
  }  
  </code></pre>
  
  <p>Please point if I am doing anything wrong/silly.  </p>