2012-06-06 19 views
5

Estoy tratando de reproducir un archivo de audio con MediaPlayer. Quiero jugar array de bytes en MediaPlayer. ¿Cómo puedo hacer esto? He comprobado thisReproducir matriz de bytes en MediaPlayer - Android

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(); 
    } 
    } 

Pero su audio no jugar. Simplemente genera muchos archivos en la tarjeta SD. Y dando este 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) 

Por favor, ayúdame. Cualquier tipo de ayuda se agradece.

Gracias

+0

añadir su código un fragmento aquí y alguien podrá ayudarlo. –

+0

Recomiendo probar la variante setDataSource que toma un desplazamiento y una longitud además del FD. ¿El archivo MP3 generado se reproduce en la aplicación de música? Además, deleteOnExit no es útil en Android/Dalvik. – dagalpin

+0

No se está reproduciendo ningún archivo en mi aplicación. Por favor, ayúdenme –

Respuesta

6

Sobre la base de sus comentarios, que está utilizando un archivo WAV para la transmisión. Convencional WAV has a header al comienzo del archivo y el resto del archivo es datos puros. Si no incluye la parte del encabezado, entonces se deben proporcionar los parámetros para que el intérprete pueda interpretar los datos (número de canales, muestras por segundo, tamaño del bloque, etc.) Como resultado, un WAV el archivo solo no es transmisible, los parámetros deben ser alimentados al reproductor.

MPEG-4 por el contrario se ha especificado que es capaz de transmitir. Contiene segmentos bien identificables que se pueden reproducir solos, por lo que siempre que el fragmento de datos contenga un encabezado, los datos posteriores pueden reproducirse. Además de su buena relación de compresión, esta es una de las razones por las que muchas radios de internet lo usan.

MediaPlayer en Android es un componente de alto nivel y no se puede acceder a los parámetros de bajo nivel que se necesitarían para reproducir un fragmento WAV. Si necesita que el origen sea WAV y no puede usar el otro streamable formats, puede probar la clase AudioTrack o OpenSL ES para obtener un acceso aún más bajo. Para AudioTrack este es un muy buen tutorial: http://audioprograming.wordpress.com/2012/10/18/a-simple-synth-in-android-step-by-step-guide-using-the-java-sdk/

+0

Hmm ... audioTrack puede sonar como el camino a seguir. – EGHDK

+0

Avísame si puedo ayudarte. – allprog

+0

el enlace wordpress está "muerto" porque el blog ahora es privado –

0

Después de escribir un byte en el archivo: se puede jugar de esta función:

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(); 
    } 

Y se puede obtener información del archivo desde aquí:

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; 
    } 
0

Prueba esto:

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(); 
    } 
} 
Cuestiones relacionadas