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?
Related
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.
Why doesn't the MediaPlayer show the video as soon as it is available. What I mean is on the IPhone when a video is played the video shows up right away. Even when returning from pause. But on the Android the screen stays black for a couple of milliseconds to a second depending on the device used and how many processes are running in the background.
I'm asking this because i want to use one of the beginning frames from my video play as a type of screenshot and currently I'm using a handler to wait 1 second before pausing the video.
Can someone tell me a quick way to make the video show up as soon as it is started or even prepared instead of my workaround?
EDIT:
Here is how I prepare my video player so It should be prepared right.
private void initVideo()
{
Log.i("VideoPlayer", "Initialize Video File" + videoFileName);
AssetFileDescriptor afd;
try {
if(videoFileName != null);
{
afd = getAssets().openFd(videoFileName);
vidplayer = new MediaPlayer();
vidplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
vidplayer.setDisplay(holder);
vidplayer.prepare();
vidplayer.setOnCompletionListener(this);
vidplayer.setOnPreparedListener(this);
//Log.i("INITVIDEO", Integer.toString(videoPausedAt));
vidplayer.seekTo(videoPausedAt);
//Log.i("VideoPlayer", "video Prepared");
videoDuration = vidplayer.getDuration()/1000;
isVideoReady = true;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e)
{
//Log.i("InitPlayer", e.getClass().toString());
e.printStackTrace();
}
}
For the background, you can get a thumbnail of the video:
private Bitmap getThumbnail(String path){
try{
return ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
}catch(Exception e){
return null;
}
}
When the video starts, you'll need to set the background back to null or you won't be able to see the video.
As for it not playing right away, it should play as soon as start() is called if you prepared it correctly, but it could be delayed if it has to load data let's say from a stream over the internet.
I have found that it is the phones fault.(mostly) Video's will show up automatically unless phone is bogged down with apps and thus loading of the video takes longer (noticed after having a voip service running).
I would like to know if there is a way to fix the duration of recording using mobile's microphone. Like when I click a button the recording should start and it should stop after 5 seconds on its own, what method do you propose me to use :-)
Edit:
Sorry for the confusion but I am using AudioRecorder class to record data and I don't think the MediaRecorder class function works properly (/at all) for the same.
If you just use a timer, I do not think that you can accurately control how much data is within the buffer when your app reads it.
I think they way to record 5 seconds of audio data is to use the technique from this class.
The code there carefully sets the size of the audio buffer so that it will call back after it has recorded data for a certain amount of time. Here is a snipped from that class.
public boolean startRecordingForTime(int millisecondsPerAudioClip,
int sampleRate, int encoding)
{
float percentOfASecond = (float) millisecondsPerAudioClip / 1000.0f;
int numSamplesRequired = (int) ((float) sampleRate * percentOfASecond);
int bufferSize =
determineCalculatedBufferSize(sampleRate, encoding,
numSamplesRequired);
return doRecording(sampleRate, encoding, bufferSize,
numSamplesRequired, DEFAULT_BUFFER_INCREASE_FACTOR);
}
Then later on your code just does this:
while (continueRecording)
{
int bufferResult = recorder.read(readBuffer, 0, readBufferSize);
//do stuff
}
since readBufferSize is just right, you will get the amount of data you want (with some slight variation)
This is all what you need.
#Override
public void onClick(View view)
{
if (view.getId() == R.id.Record)
{
new Timer().schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
files.setEnabled(true);
record.setEnabled(true);
stop.setEnabled(false);
}
});
}
}, 5000);
record.setEnabled(false);
files.setEnabled(false);
stop.setEnabled(true);
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"" + new Random().nextInt(50) + ".3gp");
adapter.add(file.getAbsolutePath());
adapter.notifyDataSetChanged();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder
.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(file.getAbsolutePath());
mediaRecorder.prepare();
mediaRecorder.start();
stop.setEnabled(true);
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
Use setMaxDuration from MediaRecorder class.
alternately
When you start recording start a new thread and put it to sleep for 5 seconds. when it wakes stop the recording.
or use a timertask which shall call the stop recording after 5 second delay.
or
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.
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