8

I am trying to play an audio file with the MediaPlayer. I want to play byte array in MediaPlayer. How can I do this? I've checked this

 public void writeSamples(byte[] samples, int length) 
{
  //  track.write( samples, 0, length);
    File tempMp3;
    try {
    tempMp3 = File.createTempFile("kurchina", ".mp3");
      tempMp3.deleteOnExit();
      FileOutputStream fos = new FileOutputStream(tempMp3);
      fos.write(samples);
      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 e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    }

But its not playing audio. It is just generating many files in SD Card. And giving this error:

 06-06 11:02:59.191: E/MediaPlayer(1831): Unable to to create media player
 06-06 11:02:59.191: W/System.err(1831): java.io.IOException: setDataSourceFD failed.:      status=0x80000000
 06-06 11:02:59.201: W/System.err(1831):  at    android.media.MediaPlayer.setDataSource(Native Method)
 06-06 11:02:59.201: W/System.err(1831):  at   android.media.MediaPlayer.setDataSource(MediaPlayer.java:749)
 06-06 11:02:59.201: W/System.err(1831):  at   org.vinuxproject.sonic.SonicTest$1.run(SonicTest.java:178)
 06-06 11:02:59.201: W/System.err(1831):  at java.lang.Thread.run(Thread.java:1096)

Please help me. Any kind of help is appreciated.

Thanks

Community
  • 1
  • 1
Krishna Suthar
  • 3,071
  • 6
  • 31
  • 37
  • add your code snippet here and someone will be able to help. – Andro Selva Jun 06 '12 at 05:27
  • I'd recommend trying the setDataSource variant that takes an offset and length in addition to the FD. Does the generated mp3 file play in the music application? Also, deleteOnExit isn't useful in Android/Dalvik. – dagalpin Jun 06 '12 at 09:20
  • No file is not playing in my application. Please help me – Krishna Suthar Jun 06 '12 at 09:23
  • Does the `samples` array contain mp3-encoded data, or just raw PCM data? – Michael Aug 27 '13 at 16:03
  • Does this work if you specify a directory with `createTempFile(String, String, File)`? Is there a difference between external/internal? Where are the temp files being created now? – Geobits Aug 27 '13 at 16:33
  • Tried using a directory of getFilesDir(), but still have the same problem. – EGHDK Aug 27 '13 at 17:36
  • Okay so if the byte array is a .mp4 file, then it seemingly works fine, but I am using a byte array that is a wave file and it won't play. Any ideas? – EGHDK Aug 27 '13 at 17:59
  • Have you tried the @dagalpin comment above - try the overload variant of setDataSource – Vrashabh Irde Aug 27 '13 at 18:09

3 Answers3

8

Based on your comments, you are using a WAV file for streaming. Conventional WAV has a header at the beginning of the file and the rest of the file is pure data. If you don't include the header part, then the parameters from it need to be provided to the player the be able to interpret the data (number of channels, samples per second, block size, etc.) As a result, a WAV file alone is not streamable, the parameters must be fed into the player.

MPEG-4 on the other hand has been specified to be capable of streaming. It contains well identifiable segments that are possible to be played alone, so as long as the data chunk contains a header, the data after it can be playable. In addition to it's good compression ratio, this is one of the reasons why many internet radios use it.

MediaPlayer in Android is a high level component and the low level parameters that would be required for playing a WAV chunk are not accessible. If you need the source to be WAV and cannot use other streamable formats, then you can try the AudioTrack class or OpenSL ES for even lower level access. For AudioTrack this is a very good tutorial: http://audioprograming.wordpress.com/2012/10/18/a-simple-synth-in-android-step-by-step-guide-using-the-java-sdk/

Community
  • 1
  • 1
allprog
  • 16,540
  • 9
  • 56
  • 97
0

After write a byte on file : you can play from this function:

 void playSound(int resid) {
        MediaPlayer eSound = MediaPlayer.create(context, resid);
        Resources res = context.getResources();
        AssetFileDescriptor afd = res.openRawResourceFd(resid);
        eSound.reset();
        eSound.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        try {
            eSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                    afd.getLength());
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            eSound.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        eSound.start();
    }

And you can get file information from here:

byte[] getFileInformation(String filepath) {
        MediaPlayer eSound = MediaPlayer.create(context, Uri.parse(filepath));
        eSound.reset();
        eSound.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        try {
            eSound.setDataSource(filepath);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            eSound.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int duration = eSound.getDuration() / 1000;

        int height = 480;
        int width = 640;
        height = eSound.getVideoHeight();
        width = eSound.getVideoWidth();

        eSound.release();
        File f = new File(filepath);
        int size = (int) f.length();
        byte[] b = new byte[16];
        System.arraycopy(convertIntToByte(size), 0, b, 0, 4);
        System.arraycopy(convertIntToByte(duration), 0, b, 4, 4);
        System.arraycopy(convertIntToByte(width), 0, b, 8, 4);
        System.arraycopy(convertIntToByte(height), 0, b, 12, 4);
        return b;
    }
laalto
  • 150,114
  • 66
  • 286
  • 303
0

Try this :

private void playMp3(byte[] mp3SoundByteArray) 
{
    try 
    {

        File path=new File(getCacheDir()+"/musicfile.3gp");

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(mp3SoundByteArray);
        fos.close();

        MediaPlayer mediaPlayer = new MediaPlayer();

        FileInputStream fis = new FileInputStream(path);
        mediaPlayer.setDataSource(getCacheDir()+"/musicfile.3gp");

        mediaPlayer.prepare();
        mediaPlayer.start();
    } 
    catch (IOException ex) 
    {
        String s = ex.toString();
        ex.printStackTrace();
    }
}
Kappa
  • 33
  • 3
Harish Godara
  • 2,388
  • 1
  • 14
  • 28