Android中怎样调用自带的Base64实现文件与字符串的编码和解码

场景

需要将某音频文件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);

然后就可以将上面编码的字符串文件解编码为语音文件并播放。 

博客园: https://www.cnblogs.com/badaoliumangqizhi/ 关注公众号 霸道的程序猿 获取编程相关电子书、教程推送与免费下载。
原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/14023019.html