I have this code:
int h = DateTime.Now.Hour;
int m = DateTime.Now.Minute;
int s = DateTime.Now.Second;
textTime.Text = h.ToString() + ":" + m.ToString() + ":" + s.ToString();
But this code is not alive.
I am not totally sure I understand your question, but maybe you want to use a StopWatch? You would need to "start" and "stop" it when necessary to get the elapsed time corrrect
var sw = new Stopwatch();
sw.Start();
sw.Stop();
var text = string.Format( "{0}:{1}:{2}", sw.Elapsed.Hours, sw.Elapsed.Minutes, sw.Elapsed.Seconds );
Related
How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);
I am having a trouble getting a timestamp string from onSensorChanged method, than write it into a Log File as this example Magnitic Timestamp column, i`m studding java by creating a sensor app.
In this app i used Calendar and Date method to get other sensors timestamp but in this case i want to use only timestamp.
Result is: 1970/01/01_08:59:59:926 but i want to get nows date and time like this : 2013/11/01_14:17:02:673
I am using the following code to write the Log File:
final SensorEventListener magniListener = new SensorEventListener() {
private float magnidT;
private long magniLogFileTimestamp;
#Override
public void onSensorChanged(SensorEvent event) {
magniLogFileTimestamp = (event.timestamp - System.nanoTime()) / 1000000L;
if (magnitimestamp != 0) {
magnidT = (event.timestamp - magnitimestamp);
magniValueX = event.values[0];
magniValueY = event.values[1];
magniValueZ = event.values[2];
//here write the sensor values and timestamp to CSV file
if (magniFile != null) {
magniFile.print(String.valueOf(sensorTimestamp
.format(magniLogFileTimestamp)));
//sensorTimestamp = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss:SSS");
magniFile.print("," + String.valueOf(magniValueX) + ","
+ String.valueOf(magniValueY) + ","
+ String.valueOf(magniValueZ));
magniFile.println();
}
}
magnitimestamp = event.timestamp;
magniX.setText("X-axis: " + String.valueOf(magniValueX));
magniY.setText("Y-axis: " + String.valueOf(magniValueY));
magniZ.setText("Z-axis: " + String.valueOf(magniValueZ));
magnDelayValue.setText("Magnitic Delay: "
+ String.valueOf(magnidT * NS2MS) + " ms");
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
magnitimestamp = 0;
magniLogFileTimestamp = 0;
}
};
I can't get it right. Any suggestions? Thank you.
If you want to get epoch in milliseconds use:
System.currentTimeMillis();
If you want to get printable date, try:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String datevalue = dateFormat.format(date);
Hope this helps.
I think the problem lies in magniLogFileTimestamp = (event.timestamp - System.nanoTime()) / 1000000L;. If you subtract the time-stamp with current time, then you get the offset time which is considerably small, hence the date value near the epoch (1970/01/01).
Instead of subtracting it, just use the event.timestamp directly.
magniFile.print(sensorTimestamp.format(event.timestamp / 1000000));
I'm following javacv Face Detection/Recognition code, there is confusion regarding face recognition.. What I'm doing is (Sorry if it sounds stupid but I'm stuck)
1) Detect Face crop it and save it to sdcard and place path in learn.txt file (Learning part)
2) Detect Face crop it and find it in existing faces whether it exists or not, but it always return nearest position even if the face doesn't exist in sample faces..
what I'm doing wrong?
// Method, I'm using to recognize face
public Integer recognizeFace(Bitmap face, Context context) {
Log.i(TAG, "===========================================");
Log.i(TAG, "recognizeFace (single face)");
float[] projectedTestFace;
float confidence = 0.0f;
int nearest = -1; // closest match -- -1 for nothing.
int iNearest;
if (trainPersonNumMat == null) {
return null;
}
Log.i(TAG, "NUMBER OF EIGENS: " + nEigens);
// project the test images onto the PCA subspace
projectedTestFace = new float[nEigens];
// Start timing recognition
long startTime = System.nanoTime();
testFaceImg = bmpToIpl(face);
// saveBmp(face, "blah");
// convert Bitmap it IplImage
//testFaceImg = IplImage.create(face.getWidth(), face.getHeight(),
// IPL_DEPTH_8U, 4);
//face.copyPixelsToBuffer(testFaceImg.getByteBuffer());
// project the test image onto the PCA subspace
cvEigenDecomposite(testFaceImg, // obj
nEigens, // nEigObjs
new PointerPointer(eigenVectArr), // eigInput (Pointer)
0, // ioFlags
null, // userData
pAvgTrainImg, // avg
projectedTestFace); // coeffs
// LOGGER.info("projectedTestFace\n" +
// floatArrayToString(projectedTestFace));
Log.i(TAG, "projectedTestFace\n" + floatArrayToString(projectedTestFace));
final FloatPointer pConfidence = new FloatPointer(confidence);
iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
confidence = pConfidence.get();
// truth = personNumTruthMat.data_i().get(i);
nearest = trainPersonNumMat.data_i().get(iNearest); // result
// get endtime and calculate time recognition process takes
long endTime = System.nanoTime();
long duration = endTime - startTime;
double seconds = (double) duration / 1000000000.0;
Log.i(TAG, "recognition took: " + String.valueOf(seconds));
Log.i(TAG, "nearest = " + nearest + ". Confidence = " + confidence);
Toast.makeText(context, "Nearest: "+nearest+" Confidence: "+confidence, Toast.LENGTH_LONG).show();
//Save the IplImage so we can see what it looks like
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "/sdcard/saved_images/" + nearest + " " + String.valueOf(seconds) + " " + String.valueOf(confidence) + " " + n + ".jpg";
Log.i(TAG, "Saving image as: " + fname);
cvSaveImage(fname, testFaceImg);
return nearest;
} // end of recognizeFace
EDIT The confidence is always negative!
Thanks in advance
i feel dumb for asking this but i have been fighting with this for a day now and i can't seem to get it working.
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
That it keeps updating the Integer I have this now;
int val = 1;
int g = 1;
val = g + val;
But it keeps saying its 2 how come?
Thanks.
I'm guessing you put all of your code in your click handler. Instead, put the variable declaration/initialization in the class level and only your addition code in your click handler. Rough code as follows:
public YourActivity extends Activity {
int val = 1;
int g = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
... //find button in here
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
val = g + val;
}
});
}
}
Because you keep setting it to 1. Initialize it outside the loop.
int val = 1;
int g = 1;
The next line:
val = g + val;
is therefore equivalent to
val = 1 + 1;
which is equivalent to
val = 2;
Not sure what you would expect here...
int val = 1; int g = 1; val = g + val;
Will always evaluate to 2. Because what happens is you take the value in g which is 1 and the value in val which is 1. This produces the sum of 2. You then take 2 and assign it to the variable val (which previously was initialized to 1).
1+1 will always be 2 (in Integer mathematics)
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
I'm guessing you want to do something like this, to produce your output a given number of times.
int timesToLoop = 10;
int summedUp = 0;
for (int i=0; i < timesToLoop; i++)
{
summedUp = i + 1;
System.out.println(i + " + " + "1 = " + summedUp);
}
How to get mp3 track duration without creating MediaPlayer instance? I just need to show mp3 song length in mp3 file list, so I think that I shouldn't create MediaPlayer object for each of tracks in the list
And another:
sometimes MediaPlayer returns wrong duration of the song ( I think its so because bitrate of those files is dinamic ). How can I get right duration of the song?
// load data file
MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
metaRetriever.setDataSource(filePath);
String out = "";
// get mp3 info
// convert duration to minute:seconds
String duration =
metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("time", duration);
long dur = Long.parseLong(duration);
String seconds = String.valueOf((dur % 60000) / 1000);
Log.v("seconds", seconds);
String minutes = String.valueOf(dur / 60000);
out = minutes + ":" + seconds;
if (seconds.length() == 1) {
txtTime.setText("0" + minutes + ":0" + seconds);
}else {
txtTime.setText("0" + minutes + ":" + seconds);
}
Log.v("minutes", minutes);
// close object
metaRetriever.release();
You can use the MediaMetadataRetriever to get the duration of a song. Use the METADATA_KEY_DURATION in combination with the extractMetadata() funciton.
Here is the Kotlin version:
var metaRetriever:MediaMetadataRetriever = MediaMetadataRetriever()
metaRetriever.setDataSource(filePath)
var out:String = ""
var txtTime:String = ""
var duration:String = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
Log.d("DURATION VALUE", duration)
var dur:Long = duration.toLong()
var seconds:String = ((dur % 60000)/1000).toString()
Log.d("SECONDS VALUE", seconds)
var minutes:String = (dur / 60000).toString()
out = minutes + ":" + seconds
if (seconds.length == 1){
txtTime = "0" + minutes + ":0" + seconds
}
else {
txtTime = "0" + minutes + ":" + seconds
}
Log.d("MINUTES VALUE", minutes)
Log.d("FORMATTED TIME", txtTime)
metaRetriever.release()
If you want to support older Android versions, you can use a 3rd party library. For example http://www.jthink.net/jaudiotagger/ works fine, though it's relatively space consuming for an Android application (a little less than 1 MB).
True programmers would of course parse the duration from the binary file without using any libraries ;) I didn't have enough skill for this.
I found this more accurate getLength with FFmpeg
int soundLength = (int) new SoxController(context, new File(""), shell).getLength(soundPath);