AudioStreaming a mediafile from web - android

I want to make simple audio streaming application but my this code is throwing exception.
Can anybody tell me whats wrong?
***public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url = "128.downloadming1.com/bollywood%20mp3/Ekk%20Deewana%20Tha%20(2012)/01%20-%20Kya%20Hai%20Mohabbat.mp3";
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(url);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
mp.start();
} catch (Exception e){
Log.i("Exception", "Exception in streaming mediaplayer e = " + e);
}
}***

Just adding to Anton's answer. prepare() function on Mediaplayer is synchronous which will block your UI thread. So its better to use setonpreparelistner and start your media player on onpreparelistner().

You code is ok, but i think, that you must add to url "http://". This must work.
UPD: if this don't work - write you exception.

Related

creating delay while playing multiple Audio files simultaneously using MediaPlayer

Outrageous number of similar questions exist here, sadly none did help me.
I am trying to play 3 Audio files simultaneously, one is .wav , the other is .3gp and the other is .mp3 . Since the size exceeds more than 1MB , I cannot use Android SoundPool here. So far, everything works well without any error. Here is my code :
MediaPlayer mp = new MediaPlayer();
MediaPlayer songPlayer = new MediaPlayer();
MediaPlayer voicePlayer = new MediaPlayer();
private String song,voice,text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time__date);
String temp;
SharedPreferences preferences1 = getSharedPreferences("musicList", MODE_PRIVATE);
song = preferences1.getString("MUSICONE", "");
SharedPreferences preferences2 = getSharedPreferences("recordList",MODE_PRIVATE);
temp = preferences2.getString("VOICEONE","");
voice = Environment.getExternalStorageDirectory()+"/myAppCache2/"+temp;
SharedPreferences preferences3 = getSharedPreferences("TextList",MODE_PRIVATE);
temp=preferences3.getString("ALARMONE","");
text=Environment.getExternalStorageDirectory()+"/myAppCache/"+temp;
try {
mp.setDataSource(text);
mp.prepare();
mp.setLooping(true);
songPlayer.setDataSource(song);
songPlayer.prepare();
songPlayer.setLooping(true);
voicePlayer.setDataSource(voice);
voicePlayer.prepare();
voicePlayer.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
songPlayer.start();
voicePlayer.start();
}
Now, my query is how do I add a delay to one ore more Audio files, Say If I want to add a delay of 5000 for voicePlayer before it loops again?
Now, my query is how do I add a delay to one ore more Audio files, Say If I want to add a delay of 5000 for voicePlayer before it loops again?
You could remove setLooping and use an OnCompletionListener instead. When you get the onCompletion callback, use postDelayed to post a Runnable that starts the player again.

Android rtsp url not loading

I'm trying to play an rtsp stream using MediaPlayer in android and the application seems to always become stuck on MediaPlayer.prepare();
The url is valid as I tested it using VLC on my desktop.
Any ideas why the application is not preparing the stream.
class InitializeService extends Thread {
#Override
public void run() {
try {
player.prepare();
Log.d("Play", "Player prepared");
} catch (IOException e) {
e.printStackTrace();
fallback();
} catch (IllegalStateException e) {
e.printStackTrace();
fallback();
}
}
}
The log statement is never reached.
Update 1:
Sorry I forgot to mention that the stream will always be in 3gp format. Here is a url rtsp://r2---sn-p5qlsu76.c.youtube.com/CiILENy73wIaGQnTXOVs7Kwo8xMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
Your stream might not be of a format supported by Android.
Check http://developer.android.com/guide/appendix/media-formats.html to see if Android supports it.
Turns out it was android l that wasn't able to play the streams.

Using MediaPlayer to play an AMR file created by MediaRecorder fails with muri null

I am writing an app that records voice from the microphone in AMR format using MediaRecorder, and then plays the data back using MediaPlayer.
That's the goal anyway.
I am fairly confident my MediaRecorder side is working, I'm producing the data file in the right place at the right data rate. Here's how I start and stop my MediaRecorder
public void OnStartRecord(View v )
{
System.out.println( "StartRecord");
try {
audioFile = File.createTempFile("amrtmp", ".amr", getApplicationContext().getFilesDir());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "Recording to " + audioFile.getAbsolutePath());
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setAudioEncodingBitRate(4750);
mRecorder.setAudioSamplingRate(8000);
mRecorder.setOutputFile(audioFile.getAbsolutePath());
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mRecorder.start();
}
public void OnStopRecord(View v )
{
System.out.println( "StopRecord");
mRecorder.stop();
mRecorder.release();
}
This works like a charm. Typical output is something like
StartRecord
Recording to /data/data/com.test.playback/files/amrtmp-235967797.amr
And when I start, then stop recording I can see that the file has been created and it has a certain amount of data in it that properly corresponds to the settings.
Side note: I detect an odd buzzing at my speaker while this runs. Any idea what that is?
When I try to play the file back however I have no end of trouble. I have tried the following:
public void OnPlay(View v )
{
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
FileInputStream FIS = null;
try {
FIS = new FileInputStream(audioFile.getAbsolutePath());
mPlayer.setDataSource(FIS.getFD());
mPlayer.prepare();
}
catch( Exception e )
{
e.printStackTrace();
}
mPlayer.start();
}
This results in nothing being played at all with the following output from MediaPlayer:
start() mURI is null
I have also tried the same code, but setting mPlayer's data source differently:
mPlayer.setDataSource(audioFile.getAbsolutePath());
This fails when prepare is called witha java.io.IOException status 0x1.
I have to imagine there is something else I need to do with MediaPlayer to set it up properly. Any suggestions?

How do I get my Media Player to double buffer?

My media player is in a service object of it's own. Here's the create code.
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = new MediaPlayer();
try {
player.setDataSource(path);
player.prepare();
} catch (Exception e) {
}
player.setLooping(false); // Set looping
}
It is streaming from online. However, it's pretty choppy 3 minutes later. I want to double buffer this to help remove that. Any ideas on how I should do this?
Have you looked at the android Double Buffer class?

Problems with MediaPlayer, raw resources, stop and start

I'm new to Android development and I have a question/problem.
I'm playing around with the MediaPlayer class to reproduce some sounds/music. I am playing raw resources (res/raw) and it looks kind of easy.
To play a raw resource, the MediaPlayer has to be initialized like this:
MediaPlayer mp = MediaPlayer.create(appContext, R.raw.song);
mp.start();
Until here there is no problem. The sound is played, and everything works fine. My problem appears when I want to add more options to my application. Specifically when I add the "Stop" button/option.
Basically, what I want to do is...when I press "Stop", the music stops. And when I press "Start", the song/sound starts over. (pretty basic!)
To stop the media player, you only have to call stop(). But to play the sound again, the media player has to be reseted and prepared.
mp.reset();
mp.setDataSource(params);
mp.prepare();
The problem is that the method setDataSource() only accepts as params a file path, Content Provider URI, streaming media URL path, or File Descriptor.
So, since this method doesn't accept a resource identifier, I don't know how to set the data source in order to call prepare(). In addition, I don't understand why you can't use a Resouce identifier to set the data source, but you can use a resource identifier when initializing the MediaPlayer.
I guess I'm missing something. I wonder if I am mixing concepts, and the method stop() doesn't have to be called in the "Stop" button. Any help?
Thanks in advance!!!
Here is what I did to load multiple resources with a single MediaPlayer:
/**
* Play a sample with the Android MediaPLayer.
*
* #param resid Resource ID if the sample to play.
*/
private void playSample(int resid)
{
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IllegalStateException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
catch (IOException e)
{
Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
}
mediaPlay is a member variable that get created and released at other points in the class. This may not be the best way (I am new to Android myself), but it seems to work. Just note that the code will probably fall trough to the bottom of the method before the mediaPlayer is done playing. If you need to play a series of resources, you will still need to handle this case.
this is how MediaPlayer.create method works to open a raw file:
public static MediaPlayer create(Context context, int resid) {
try {
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
if (afd == null) return null;
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
return mp;
} catch (IOException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
} catch (IllegalArgumentException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
} catch (SecurityException ex) {
Log.d(TAG, "create failed:", ex);
// fall through
}
return null;
}
Or, you could access the resource in this way:
mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.package.name/raw/song"));
where com.package.name is the name of your application package
You can use
mp.pause();
mp.seekTo(0);
to stop music player.
Finally, the way it works for me:
public class MainStart extends Activity {
ImageButton buttonImage;
MediaPlayer mp;
Boolean playing = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonImage = (ImageButton)findViewById(R.id.ButtonID);
buttonImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(playing){
mp.stop();
playing = false;
}else{
mp = MediaPlayer.create(getApplicationContext(), R.raw.sound_u_want);
mp.start();
playing = true;
}
}
});
}
}
MR. Rectangle, this message maybe too late for it, but I proudly write these codes to your idea: I have mp for mediaplayer and sescal9 is a button.
....
if(btnClicked.getId() == sescal9_ornek_muzik.getId())
{
mp.start();
mp.seekTo(380);
mp2.start();
mp2.seekTo(360);
mp3.start();
mp3.seekTo(340);
...
}
Recheck your passing parameters not null
Possible reasons
Context may be null
Your media file may be corrupted

Categories

Resources