i could need some help with that. here is the problem and what i have done until now.
problem:
i want to play a pcm file that i recorded before. as this file can be larger, i play it by using audiotrack. this works quite nice. but i dont want the activity to freeze. i already tried thread and so on, now im working on the asynctask but the activity still is not responding.
this is what i got:
in the ui activity, i create a new waveplayer object and try to run it.
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Handles ShortClicks for ListView
*/
OnItemClickListener itemlistener = new OnItemClickListener(){
MediaPlayer mp=null;
String currentlyplaying = null;
#Override
public void onItemClick(AdapterView<?> adaptview, View clickedview, int position,
long id) {
String pathtofile = (String) adaptview.getItemAtPosition(position);
if(pathtofile.contains(".wav"))
{
//HQ!
if(mp==null)
{
clickedview.setSelected(true);
try
{
WavePlayer t = null;
//TODO: //add thread waveplayer to play file!
try {
t = new WavePlayer(pathtofile);
t.execute((Void)null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clickedview.postDelayed(new Deselector(clickedview, t), 1000);
currentlyplaying = pathtofile;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
else
{
}
}
else{
//NO HQ
//you dont need to know that :)
}
}
};
the class deselector:
/**
* This Runnable tries to deselect the view after playing the audio file.
* #author quant
*
*/
class Deselector implements Runnable
{
View view = null;
AsyncTask thread;
Deselector(View view, AsyncTask t)
{
this.view = view ;
this.thread = t;
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
view.setSelected(false);
thread.cancel(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
everything concerning playback works nice, i can hear my voice and the playback itself works fine... but still the gui in the main activity does freeze/is not responding.
hope someone can help.
thanks in advance
markus
i solved it by using a remote service. i'm happy with this solution because i had one running for other purpose yet. now the interface is responsive again.
Related
I have a little problem. In my android app, i have to connect to an online server.
The connection should be called with an click-button an as an backround service. I know that I must put the network connection in a thread, but i don't know how it works.
I put the call in a own method wich creates a thread but at compilation i got a error message.
here is my code:
Button:
ImageView refresher = (ImageView)findViewById(R.id.imgRefresh);
refresher.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
httpThread();
}
});
thread method:
private void httpThread(){
final Handler h = new Handler();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
h.post(new Runnable(){
#Override
public void run() {
try{
vomServerholenUndSpeichern();
FileInputStream inStream = null;
try {
inStream = openFileInput("test.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
leseDatei(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createListView("test.xml");
System.out.println(inStream);
drawListView();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
});
thread.start();
}
Can someone help me to fix the problem?
You have to use AsyncTask, is not difficult.
AsyncTask are necessary to avoid block UI during your connection operation, the method doInbackGround of AsyncTask is used for this kind of operations (it runs in a thread different from the UI), while int the onPostExecute (this run on the UI) of the task you will manage your httpResult;)
I have a program which automatically moves objects around the screen, drawing them on an ImageView. On some occasions, two or more objects will be moved in succession. At present, the user sees only the final configuration. I would like to insert a pause between them, so that intermediate configurations are seen.
The code below is intended to achieve this by setting a busy flag and sleeping on a separate thread. However, it does not update the screen in between. The effect is a long pause followed by the final view.
Advice would be welcome!
private boolean busy = false;
private void slowMoveObject(<args>) {
Thread th = new Thread() {
public void run() {
int waitCount = 0;
while (busy) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
waitCount++;
if (waitCount > 50) break;
}
busy = true;
moveObject(<args>);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
busy = false;
};
};
th.run(); // delay
}
So I am trying to create a "strobe" light effect in my app.
To do this I need a time delay, one of 100ms the other of 20.
Here is the code I'm using.
Thread timer = new Thread();
long longTime = 100;
long shortTime = 20;
for (int x = 0; x < 2000000; x++)
{
layout.setBackgroundColor(background);
try {
timer.sleep(longTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.setBackgroundColor(backgroundBlack);
try {
timer.sleep(shortTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The issue I have is that when I click the button to call that code, nothing happens. So I've done a bit of debugging and am pretty sure it is the timing call. I have never programmed in Java before so I am unsure how to call a Thread Sleep.
You could use a Handler as below to achieve this.
public class Strobe extends Activity {
private LinearLayout mLinearLayout;
private Handler mHander = new Handler();
private boolean mActive = false;
private boolean mSwap = true;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mSwap) {
mLinearLayout.setBackgroundColor(Color.WHITE);
mSwap = false;
mHander.postDelayed(mRunnable, 20);
} else {
mLinearLayout.setBackgroundColor(Color.BLACK);
mSwap = true;
mHander.postDelayed(mRunnable, 100);
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLinearLayout = (LinearLayout) findViewById(R.id.strobe);
startStrobe();
}
private void startStrobe() {
mActive = true;
mHander.post(mRunnable);
}
}
Set a Theme to the Activity to make it full screen.
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
I think this article would benefit you.
http://oreilly.com/catalog/expjava/excerpt/index.html
specifically this
http://oreilly.com/catalog/expjava/excerpt/index.html#EXJ-CH-6-FIG-1
Your problem is that you are not running in the Thread. In order to run code in the thread you must override it's run() method. Based on your current code, the following may capture what you want to do.
Thread timer = new Thread(){
public void run(){
long longTime = 100;
long shortTime = 20;
for (int x = 0; x < 2000000; x++)
{
layout.setBackgroundColor(background);
try {
Thread.sleep(longTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.setBackgroundColor(backgroundBlack);
try {
Thread.sleep(shortTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
timer.start();
However, threads don't play that well with the Android OS. For your application, it may be better to use Android services. See http://developer.android.com/guide/topics/fundamentals/services.html .
I am trying to figure out how to have a progress bar that says "Loading. Please Wait..." while my media player prepares a streaming file. What occurs now is that it displays after the song is prepared. how can i fix this?
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
/*dubstep stream*/
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
dubstepMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dubstepMediaPlayer.start();
if(dubstepMediaPlayer.isPlaying()){
mediaPlayerLoadingBar.dismiss();
}`
EDIT:
This is the code I have now:
`switch(pSelection){
case 1:
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute(){
mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
try {
dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
return null;
}
protected void onPostExecute(Void result){
//mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true)
dubstepMediaPlayer.prepareAsync();
dubstepMediaPlayer.start();
mediaPlayerLoadingBar.dismiss();
}
}.execute();`
If someone Still facing this problem here is the code below
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
if(translation.equals("NIV"))
{
if(AudioPlaying==false)
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(Main.this);
mediaController = new MediaController(Main.this);
}
else
mediaController.show();
}
else
Toast.makeText(getBaseContext(), "عفوا, جاري تحميل ملفات الصوت الخاصة بترجمة الفانديك ", Toast.LENGTH_LONG).show();
pd = new ProgressDialog(Main.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
//Thread.sleep(5000);
try
{
mediaPlayer.setDataSource(AudioUrlPath);
mediaPlayer.prepare();
mediaPlayer.start();
AudioPlaying=true;
}
catch (IOException e) {
Log.e("AudioFileError", "Could not open file " + AudioUrlPath + " for playback.", e);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
//b.setEnabled(true);
}
}
};
task.execute((Void[])null);
The issue lies in that you are not doing anything asynchronously here, and you should be. You should use an AsyncTask to do your work.
Take a look at 'the 4 steps', as detailed here:
The 4 steps
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
EDIT:
You can create an anonymous inner class to do your bidding, which may be similar to how you are creating your onClick handler. In your onClick do something like this:
//pseudo-code...
onClick(View v, ...) {
new AsyncTask<Generic1, Generic2, Generic3>() {
protected void onPreExecute() {
// do pre execute stuff...
}
protected Generic3 doInBackground(Generic1... params) {
// do background stuff...
}
protected void onPostExecute(Generic3 result) {
// do post execute stuff...
}
}.execute();
}
Don't forget to keep an eye on your generics here!
Here is the activity class.Here i am showing the way only.
package com.android.mediaactivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class MediaActivity extends Activity
{
public LinearLayout mainLayout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(LinearLayout)findViewById(R.id.mainlinear);
MediaPlayer media=new MediaPlayer(this);
media.startPlayer();
}
}
Here is mediaplayerclass.
package com.android.mediaactivity;
import java.io.IOException;
import android.media.MediaPlayer.OnPreparedListener;
public class MediaPlayer implements OnPreparedListener {
MediaActivity mediaActivity;
android.media.MediaPlayer mediaPlayer;
public MediaPlayer(MediaActivity mediaActivity) {
this.mediaActivity = mediaActivity;
}
public void startPlayer() {
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource("");
mediaPlayer.prepareAsync();
toggleProgress(true);
} catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onPrepared(android.media.MediaPlayer mp) { toggleProgress(false); mediaPlayer.start(); }
public void toggleProgress(final boolean show) {
mediaActivity.runOnUiThread(new Runnable() {
public void run() {
if (show) mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.VISIBLE);
else mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.INVISIBLE);
}
});
}
}
}
}
And here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="#+id/mainlinear"
android:visibility="invisible">
<ProgressBar android:id="#+id/ProgressBar01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
When you say prepare on the underlying mediaplayer object, internally it really does some preparation like - setting up the extractor for the file, setting up the audio decoder to decode the encoded audio file and setting up the audio sink to play the raw audio data that was decoded from the decoder. Now all this will take time, it is not instantaneous.
So in your original code, you check if the mediaplayer isPlaying and then dismiss it but the problem is at that point of time the mediaplayer is not playing the audio yet and thus your dismiss is never called so it always visible.
What you need to do is implement the listener MediaPlayer.OnPreparedListener and when the method onPrepared is called in your application call the dismiss mediaPlayerLoadingBar.dismiss(); in that method.
Here is my solution :
The prepareAsync function used to prepare the audio and it is a non blocking operation (it is not blocking the main thread of the app).
Then I used the callback setOnPreparedListener to get notified when the
prepareAsync return, and the audio is ready
public void playAudio(String audioFile){
//init the progress dialog
final ProgressDialog progressDialog = new ProgressDialog(SubjectActivity.this);
try {
progressDialog.setCancelable(false);
progressDialog.setMessage(" Waiting to Prepare ...");
progressDialog.show();
// pass the url file to the media player
mediaplayer.setDataSource(audioFile);
mediaplayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the callback gets called when prepareAsync audio file become ready,
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaplayer.start();
// cancel the dialog
progressDialog.cancel();
}
});
}
Finally found out:
Guys very Imp point:
After setting url
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
I have added prepare_sync() and added handler cause it was crashing for big files
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.prepareAsync();
ProgressDialog progressDialog = ProgressDialog.show(Player.this,
"Loading Title", "Loading Message");
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
});
// might take long! (for buffering, etc)
mediaPlayer.start();
}
},500);
This code will add progressbar too.
Points:
set url
prepareasync
OnPreparedlistener
Progressbar
mp.start-done
This is my way of doing btw I have heard there is alternative Exoplayer have a look at that too !
I have managed to get a working video player that can stream rtsp links, however im not sure how to display the videos current time position in the UI, i have used the getDuration and getCurrentPosition calls, stored this information in a string and tried to display it in the UI but it doesnt seem to work
**in main.xml:**
TextView android:id="#+id/player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="1px"
android:text="#string/cpos"
/>
**in strings.xml:**
string name="cpos">"" /string>
**in Player.java**
private void playVideo(String url) {
try {
media.setEnabled(false);
if (player == null) {
player = new MediaPlayer();
player.setScreenOnWhilePlaying(true);
} else {
player.stop();
player.reset();
}
player.setDataSource(url);
player.getCurrentPosition();
player.setDisplay(holder);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.prepareAsync();
player.setOnBufferingUpdateListener(this);
player.setOnCompletionListener(this);
} catch (Throwable t) {
Log.e(TAG, "Exception in media prep", t);
goBlooey(t);
try {
try {
player.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v(TAG, "Duration: ===> " + player.getDuration());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Runnable onEverySecond = new Runnable() {
public void run() {
if (lastActionTime > 0
&& SystemClock.elapsedRealtime() - lastActionTime > 3000) {
clearPanels(false);
}
if (player != null) {
timeline.setProgress(player.getCurrentPosition());
//stores getCurrentPosition as a string
cpos = String.valueOf(player.getCurrentPosition());
System.out.print(cpos);
}
if (player != null) {
timeline.setProgress(player.getDuration());
//stores getDuration as a string
cdur = String.valueOf(player.getDuration());
System.out.print(cdur);
}
if (!isPaused) {
surface.postDelayed(onEverySecond, 1000);
}
}
};
Your code snippet looks significantly like my vidtry sample. getCurrentPosition() and getDuration() works for HTTP streaming, such as for use in updating the progress bar.
I have not tried vidtry with an RTSP video stream, mostly because I don't know of any.
Check the SDP response from the server to ensure that it is sending the duration in the response (live streams don't have a recognizable time and that may cause the client to not provide this information.)
E.g. a live feed will look like:
a=range:npt=0-
Whereas a VoD clip should look like:
a=range:npt=0-399.1680
If getCurrentPosition() doesn't work, but you know the Duration (either getDuration() works or you have an alternate way of getting this information; you could calculate it by watching the buffering events and tracking this your self. Your approach is the more desirable approach than this one.
If I got you right, you want to show in a TextView elapsed time e.g. hh:mm:ss?
If so, I'll give you a little walkthrough on how to do that.
private TextView mElapsedTimeText;
private VideoView mVideoView;
private Thread mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
/* here goes your code */
// let's assume that your IDs are elapsedId and videoId
mElapsedTimeText = (TextView) findViewById(R.id.elapsedId);
mVideoView = (VideoView) findViewById(R.id.videoId);
mThread = new Thread() {
#Override
public void run() {
mElapsedTime.setText(getNiceString());
mVideoView.postDelayed(mThread, 1000);
}
}
/* here goes your code */
}
public String getNiceString() {
String result = "";
int position = mVideoView.getCurrentPosition();
/* here goes your code */
//result is hh:mm:ss formatted string
return result;
}
#Override
public void onPrepared(MediaPlayer mp) {
/* here goes your code */
// you have to trigger the process somewhere
mVideoView.postDelayed(mThread, 1000);
/* here goes your code */
}
And one more thing I forgot to mention. In order to make this work your activity class has to implement the OnPreparedListener interface.
I hope you or someone else will find this post useful.
Best regards,
Igor