場景
需要將某音頻文件mp3格式編碼成字符串並能再將其轉換為字符串。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
首先新建一個工具類File2StringUtils並在工具類中新建方法實現將文件編碼為字符串
public static String fileToBase64(InputStream inputStream) { String base64 = null; try { byte[] bytes = new byte[inputStream.available()]; int length = inputStream.read(bytes); base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return base64; }
然后在res下新建raw目錄,在此目錄下存放一個mp3的音頻文件。
然后在需要將文件編碼為字符串的地方
InputStream is = getResources().openRawResource(R.raw.b32); msg = File2StringUtils.fileToBase64(is);
然后就可以將此mp3編碼成Base64格式的字符串
然后在工具類中再新建一個解碼的方法 ,通過
byte[] mp3SoundByteArray = Base64.decode(content, Base64.DEFAULT);// 將字符串轉換為byte數組
剩下的就可以根據自己的需求將字節數據進行相應的操作,比如這里是將其存儲到臨時文件中
並進行播放
public static void playMp3(String content) { try { byte[] mp3SoundByteArray = Base64.decode(content, Base64.DEFAULT);// 將字符串轉換為byte數組 // create temp file that will hold byte array File tempMp3 = File.createTempFile("badao", ".mp3"); tempMp3.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tempMp3); fos.write(mp3SoundByteArray); fos.close(); // Tried reusing instance of media player // but that resulted in system crashes... MediaPlayer mediaPlayer = new MediaPlayer(); // Tried passing path directly, but kept getting // "Prepare failed.: status=0x1" // so using file descriptor instead FileInputStream fis = new FileInputStream(tempMp3); mediaPlayer.setDataSource(fis.getFD()); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException ex) { String s = ex.toString(); ex.printStackTrace(); } }
然后在需要將此字符串編碼解碼為語音文件的地方
File2StringUtils.playMp3(dataContent);
然后就可以將上面編碼的字符串文件解編碼為語音文件並播放。