本文介绍了Android - 从字节播放 mp3[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 byte[] 中有我的 mp3 文件(从服务下载),我想在我的设备上播放它,类似于播放文件的方式:

I have my mp3 file in byte[] (downloaded from an service) and I would like to play it on my device similar to how you can play files:

MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();

但我似乎找不到办法做到这一点.我不介意将文件保存到手机然后播放.如何播放文件,或下载然后播放?

But I can't seem to find a way to do it. I wouldn't mind saving file to phone and then playing it. How can I play the file, or download then play it?

推荐答案

好的,谢谢大家,但我需要从 byte[] 播放 mp3,因为我从 .NET webservice 得到它(不想动态存储在服务器上生成 mp3).

OK, thanks to all of you but I needed to play mp3 from byte[] as I get that from .NET webservice (don't wish to store dynamically generated mp3s on server).

最后 - 有许多问题"可以播放简单的 mp3...这里是任何需要它的人的代码:

In the end - there are number of "gotchas" to play simple mp3... here is code for anyone who needs it:

private MediaPlayer mediaPlayer = new MediaPlayer();
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();
    }
}

我在 4 年前写了这个答案 - 很明显,从那时起很多事情都发生了变化.请参阅 Justin 关于如何重用 MediaPlayer 实例的评论.另外,我不知道 .deleteOnExit() 现在是否适合您 - 请随时提出改进建议,以免临时文件堆积.

I've wrote this answer more than 4 years ago - obviously lots of things have changed since then. See Justin's comment on how to reuse MediaPlayer instance. Also, I don't know if .deleteOnExit() will work for you now - feel free to suggest improvement so that temp files do not pile up.

这篇关于Android - 从字节播放 mp3[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:55