Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feeding data from memory to MediaPlayer

Tags:

android

Scenario: Have encrypted mp3 files in my .apk. Need to decrypt and send to MediaPlayer object.

Problem: After I read the files and decrypt them, how do I get MediaPlayer to play them ?

Now. MediaPlayer has 4 versions of setDataSource().

setDataSource(String path)
setDataSource(FileDescriptor fd)
setDataSource(FileDescriptor fd, long offset, long length)
setDataSource(Context context, Uri uri)

None of which are ideal for the situation. Guess ideal would be to give MediaPlayer an InputStream ?

Possible solutions:

  • Write decrypted data to file play that file. A lot of IO overhead.
  • Create a dummy http server (ServerSocket ?) and pass the url to MediaPlayer. Again, messy. Am I even allowed to create a socket.

Does anyone have a better solution ?

like image 627
olafure Avatar asked Nov 25 '10 22:11

olafure


People also ask

Which method is used to release the resources while using MediaPlayer?

MediaPlayer release() method, from Android Dev: Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer.

What is MediaPlayer in Android?

android.media.MediaPlayer. MediaPlayer class can be used to control playback of audio/video files and streams. MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread. If registering callbacks, the thread must have a Looper.

What class in Android can be used to play an audio file?

One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup.


1 Answers

byte[] callData = ...;
String base64EncodedString = Base64.encodeToString(callData, Base64.DEFAULT);

try
{
    String url = "data:audio/amr;base64,"+base64EncodedString;
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(url);
    mediaPlayer.prepare();
    mediaPlayer.start();
}
catch(Exception ex){
    ...
}
like image 195
A. Serediuk Avatar answered Nov 15 '22 03:11

A. Serediuk