如何在android中播放Base64编码的音频?

时间:2016-10-27 05:18:02

标签: android audio media-player avaudioplayer audio-streaming

到目前为止我一直在尝试: -

  • 拥有音频文件的Base64编码字符串。

现在我在这里尝试这样玩。

public void PlayAudio(String base64EncodedString){
        try
        {
            String url = "data:audio/mp3;base64,"+base64EncodedString;
            Uri uri = Uri.parse(url);
            mediaPlayer.setDataSource(MainActivity.this, uri);
            /*mediaPlayer.prepare();*/
            mediaPlayer.start();
        }
        catch(Exception ex){
            System.out.print(ex.getMessage());
        }
    }

private void playMp3(byte[] mp3SoundByteArray) {
        try {
            // create temp file that will hold byte array
            File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
            tempMp3.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tempMp3);
            fos.write(mp3SoundByteArray);
            fos.close();

            // resetting mediaplayer instance to evade problems
            mediaPlayer.reset();

            // In case you run into issues with threading consider new instance like:
            // 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();
        }
    }

但音频没有播放。

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

在播放之前,您实际上需要解码Base64编码的String。请检查解码程序here