Commit 949a2289 authored by CallisteHanriat's avatar CallisteHanriat
Browse files

apply new correctives

parent fb51193a
......@@ -3,7 +3,7 @@
package="org.lp20.aikuma2"
android:versionCode="010005"
android:versionName="0.8.4">
<uses-sdk android:minSdkVersion="16"/>
<uses-sdk android:minSdkVersion="14"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
......
......@@ -16,6 +16,7 @@ import org.lp20.aikuma2.R;
import com.musicg.wave.Wave;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
......@@ -144,17 +145,12 @@ public class ElicitationMode extends AikumaActivity{
* Copied from RespeakingSelection.java
*/
public class FilebrowserDialogFragment extends DialogFragment {
ListView listElement;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_select_file_frag, null);
listElement = (ListView) view.findViewById(R.id.listItemFile);
Dialog dialog = null;
ListFolderAdapter adapter = new ListFolderAdapter(getActivity(), mFileList, mPath, selectedFileType);
listElement.setAdapter(adapter);;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
Dialog dialog = new Dialog(getActivity());
AlertDialog.Builder builder = new Builder(getActivity());
if(mFileList == null) {
Toast.makeText(getActivity(), "No files to display", Toast.LENGTH_SHORT).show();
......@@ -162,16 +158,20 @@ public class ElicitationMode extends AikumaActivity{
dialog = builder.create();
return dialog;
}
listElement.setOnItemClickListener(new OnItemClickListener() {
builder.setTitle("Import file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dismiss();
mChosenFile = mFileList[position];
mChosenFile = mFileList[which];
Log.i(TAG, "mChosenFile: " + mChosenFile);
mPath = new File(mPath, mChosenFile);
if (mPath.isDirectory()) {
if (!isSelectionnable(mPath)) {
Log.d("mPath", mPath.getAbsolutePath() + " is not selectionnable");
Log.d("not selectionnable", "not selectionnable");
loadFileList(mPath, fileType);
if(mFileList.length > 0)
showAudioFilebrowserDialog();
......@@ -179,21 +179,15 @@ public class ElicitationMode extends AikumaActivity{
Log.d("mPath", mPath.getAbsolutePath() + " is selectionnable");
actionSelectedFile();
}
} else {
if (fileType==".jpg") {
Toast.makeText(ElicitationMode.this, "Selected folder: " + mPath, Toast.LENGTH_LONG).show();
}
if (fileType==".avi") {
Toast.makeText(ElicitationMode.this, "Selected video: " + mPath, Toast.LENGTH_LONG).show();
}
} else if (mPath.isFile() && mPath.toString().contains(".txt")) {
actionSelectedFile();
} else {
Toast.makeText(ElicitationMode.this, "ERROR : Is not txt file", Toast.LENGTH_SHORT).show();
}
}
});
dialog.setContentView(view);
dialog.setTitle("Import file");
dialog.show();
dialog = builder.show();
return dialog;
}
}
......@@ -212,11 +206,6 @@ public class ElicitationMode extends AikumaActivity{
i++;
}
return files.length == i && i>0;
case ElicitationMode.TEXT_MODE:
while(files[i].isFile() && files[i].getAbsolutePath().contains(".mp4")) {
i++;
}
return files.length == i;
case ElicitationMode.VIDEO_MODE:
while( i < files.length && files[i].isFile() && (files[i].getAbsolutePath().contains(".mp4") || files[i].getAbsolutePath().contains(".avi"))) {
i++;
......
......@@ -3,6 +3,7 @@ package org.lp20.aikuma.ui;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
......@@ -76,6 +77,10 @@ public class RecordElicitation extends AikumaActivity {
private SharedPreferences prefsUserSession;
private String strFolderDate;
private RecordingLig recordingLig;
/**
* the "linker" file
*/
private File textFile;
private BufferedWriter bufferedWriter;
private int choiceMode;
......@@ -136,7 +141,7 @@ public class RecordElicitation extends AikumaActivity {
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.e(TAG,"text file could not be found: " + e1);
Toast.makeText(this, "An error occurred, the text file could not be found", Toast.LENGTH_LONG).show();
Toast.makeText(this, "An error occurred, the resource file could not be found", Toast.LENGTH_LONG).show();
try {
bufferedWriter.close();
} catch (IOException e) {
......@@ -144,7 +149,7 @@ public class RecordElicitation extends AikumaActivity {
}
this.finish();
} catch (IOException e) {
Toast.makeText(this, "Something weird happened. It might be that the text file was empty.", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Something weird happened. It might be that the resource file was empty.", Toast.LENGTH_LONG).show();
Log.e(TAG,"No more sentences to display or an error occurred: " + e);
try {
bufferedWriter.close();
......@@ -178,7 +183,7 @@ public class RecordElicitation extends AikumaActivity {
videoView.setVideoPath(images[entityId].getAbsolutePath());
videoView.setDrawingCacheEnabled(true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(this.getResources(), thumb);
videoView.setBackground(bitmapDrawable);
videoView.setBackgroundDrawable(bitmapDrawable);
videoView.setVisibility(View.GONE);
videoView.setVisibility(View.VISIBLE);
}
......@@ -281,8 +286,8 @@ public class RecordElicitation extends AikumaActivity {
e.printStackTrace();
}
if (choiceMode == ElicitationMode.TEXT_MODE)
goToGoodPlaceInTextFile();
/*if (choiceMode == ElicitationMode.TEXT_MODE)
goToGoodPlaceInTextFile();*/
isNewSession = false;
} else {
......@@ -598,6 +603,7 @@ public class RecordElicitation extends AikumaActivity {
bufferedWriter.write(".../" + images[entityId].getParentFile().getName() + "/" + images[entityId].getName() + " ; "+
".../" + new File(filename).getParentFile().getName() + "/"+new File(filename).getName().replace(".wav", "_"+entityId+".wav"));
bufferedWriter.newLine();
bufferedWriter.flush();
}
} catch (IOException e) {
Log.e(TAG, "error when saving the recroding: " + e);
......@@ -683,7 +689,14 @@ public class RecordElicitation extends AikumaActivity {
}
} else if (choiceMode == ElicitationMode.IMAGE_MODE || choiceMode == ElicitationMode.VIDEO_MODE) {
File f = new File(ptrSelectedReference);
return f.listFiles().length;
return f.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
return !pathname.isHidden();
}
}).length;
}
return nbLine;
}
......@@ -748,7 +761,7 @@ public class RecordElicitation extends AikumaActivity {
public void onClick(DialogInterface dialog,
int which) {
if (entityId<numberOfEntities && textFile.exists()) {
if (entityId<numberOfEntities) {
saveCurrentState();
}
if ((choiceMode == ElicitationMode.IMAGE_MODE || choiceMode == ElicitationMode.VIDEO_MODE) && bufferedWriter != null) {
......
package org.lp20.aikuma.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.lp20.aikuma.Aikuma;
import org.lp20.aikuma.MainActivity;
import org.lp20.aikuma.audio.SimplePlayer;
import org.lp20.aikuma.audio.record.Recorder;
import org.lp20.aikuma.audio.record.Microphone.MicException;
import org.lp20.aikuma.model.Language;
import org.lp20.aikuma.model.MetadataSession;
import org.lp20.aikuma.model.Recording;
import org.lp20.aikuma.model.RecordingLig;
import org.lp20.aikuma.util.AikumaSettings;
import org.lp20.aikuma.util.FileIO;
import org.lp20.aikuma2.R;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class RecordElicitationImage extends AikumaActivity {
public static final String TAG = "RecordElicitationImage";
private UUID recordUUID;
private Recorder recorder;
protected long sampleRate = 16000l;
private boolean recording = false;
private Bitmap picture;
private int imageId = 0;
private String folderPath;
private ListenFragment fragment;
private Boolean isNewSession = true;
private Date date;
private SharedPreferences prefsUserSession;
private String strFolderDate;
private RecordingLig recordingLig;
private File[] images;
/**
* the progress bar used to display the user's progression.
*/
private InterleavedSeekBar progressBar;
private Language recordLang;
private int numberOfImages;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elicitation_image);
recordUUID = UUID.randomUUID();
// retrieving metadata
prefsUserSession = getSharedPreferences(getString(R.string.userSession), MODE_PRIVATE);
initSession();
File f = new File(folderPath);
images = f.listFiles();
initProgressBars();
loadImage();
numberOfImages = countNumberOfImages();
TextView tv = (TextView) findViewById(R.id.elicit_phrase_number);
tv.setText("" + imageId);
TextView tv_total = (TextView) findViewById(R.id.elicit_total_number);
tv_total.setText(" / " + numberOfImages);
fragment = (ListenFragment) getFragmentManager().findFragmentById(R.id.phrase_player);
}
private void loadImage() {
ImageView selected_photo = (ImageView) findViewById(R.id.img_orig);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(images[imageId].getAbsolutePath(), options);
int nh = (int) ( bitmap.getHeight() * (512.0 / bitmap.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
selected_photo.setImageBitmap(scaled);
}
private int countNumberOfImages() {
// TODO Auto-generated method stub
File f = new File(folderPath);
return f.listFiles().length;
}
@SuppressWarnings("unchecked")
private void initSession() {
if (prefsUserSession.getBoolean(getString(R.string.sessionActive), false)) {
strFolderDate=prefsUserSession.getString(getString(R.string.sessionDate), "");
recordLang = new Language(prefsUserSession.getString(getString(R.string.language_name), ""),
prefsUserSession.getString(getString(R.string.languageCode), ""));
try {
date = new SimpleDateFormat().parse(strFolderDate);
} catch (ParseException e) {
date = new Date();
e.printStackTrace();
}
SharedPreferences.Editor ed = prefsUserSession.edit();
folderPath = prefsUserSession.getString(getString(R.string.sessionInputFile), "");
imageId = prefsUserSession.getInt(getString(R.string.currentLine), 0);
ed.clear();
ed.commit();
goToPreviousState();
isNewSession = false;
} else {
folderPath = getIntent().getStringExtra(ElicitationMode.importFileName);
Log.i(TAG, "Selected file: " + folderPath);
setMetadataSession();
imageId=0;
recordLang = MetadataSession.getMetadataSession().getRecordLanguage();
strFolderDate = new SimpleDateFormat("yyMMdd-HHmmss").format(date);
}
}
/**
* Called to going to the previous state (phraseID and others graphical attributes
*/
private void goToPreviousState() {
String phrase;
int i = 0;
}
/**
* Called to create the metadata session
*/
private void setMetadataSession() {
if (getIntent() != null) {
Intent metadataIntent = getIntent();
Bundle respeakingBundle = metadataIntent.getBundleExtra(RecordingMetadataLig.metaBundle);
int gender = respeakingBundle.getInt(RecordingMetadataLig.metaSpkrGender);
Language recordLang = respeakingBundle.getParcelable(RecordingMetadataLig.metaRecordLang);
Language motherTong = respeakingBundle.getParcelable(RecordingMetadataLig.metaMotherTong);
ArrayList<Language> rspkLanguages = respeakingBundle.getParcelableArrayList(RecordingMetadataLig.metaLanguages);
String regionOrigin = respeakingBundle.getString(RecordingMetadataLig.metaOrigin);
String speakerName = respeakingBundle.getString(RecordingMetadataLig.metaSpkrName);
int speakerAge = respeakingBundle.getInt(RecordingMetadataLig.metaSpkrBirthYr);
Log.d("gender", ""+gender);
int speakerGender = gender == 1 ?
RecordingMetadataLig.GENDER_MALE : RecordingMetadataLig.GENDER_FEMALE;
MetadataSession.getMetadataSession().setSession(recordLang, motherTong,
rspkLanguages, regionOrigin, speakerName, speakerAge, speakerGender);
Bundle bundle = getIntent().getBundleExtra(RecordingMetadataLig.metaBundle);
try {
date = new SimpleDateFormat().parse(bundle.getString(RecordingMetadataLig.metaDate));
} catch (ParseException e1) {
date = new Date();
} catch (Exception e) {
Log.e(TAG, "Exception caught: " + e);
}
}
}
/**
* called to set progressionBar behavior
* progressionBar is not modifiable by hand
*/
private void initProgressBars() {
progressBar = (InterleavedSeekBar) findViewById(R.id.seek_elicit_progression);
progressBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
int originalProgress;
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (fromUser) {
seekBar.setProgress(originalProgress);
}
}
public void onStopTrackingTouch(SeekBar _seekBar) {};
public void onStartTrackingTouch(SeekBar _seekBar) {
originalProgress = progressBar.getProgress();
};
});
}
/**
* Function called to restore the recordingLig by a json file.
*/
private void restoreMetaDataFromJson() {
if (imageId > 0) {
File metadataFile = new File(FileIO.getOwnerPath().getAbsolutePath() + "/"+ "recordings" + "/" +this.strFolderDate + "_"+recordLang.getCode()+"_"+Aikuma.getDeviceId(),
this.strFolderDate + "_" + recordLang.getCode() + "_" + Aikuma.getDeviceId() + "_" + (imageId-1) + RecordingLig.METADATA_SUFFIX);
Log.d("metadataFile : ", "metadataFile : " + metadataFile.getAbsolutePath());
try {
recordingLig = RecordingLig.read(metadataFile);
recordingLig.setRecordingUUID(recordUUID);
recordingLig.setDeviceName(Aikuma.getDeviceName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Function called when we need to initialize the recordingLig object
* used to write json and wav files.
*/
private void setRecordingLig() {
if (isNewSession) {
int duration = recorder.getCurrentMsec();
String deviceName = Aikuma.getDeviceName();
String androidID = Aikuma.getAndroidID();
ArrayList<String> speakerIds = new ArrayList<String>();
Double latitude = MainActivity.locationDetector.getLatitude();
Double longitude = MainActivity.locationDetector.getLongitude();
String suffix = new File(folderPath).getName().replace(".txt", "").length() >= 10 ? new File(folderPath).getName().substring(0, 10)
: new File(folderPath).getName().replace(".txt", "");
String idDevice = Aikuma.getDeviceId();
String name = strFolderDate + "_" +
MetadataSession.getMetadataSession().getRecordLanguage().getCode()
+ "_" + idDevice;
// + "_elicit_" + new File(eliciTextFile).getName().substring(0,10);
// + "_" + eliciTextFile.substring(0, 10) + "_" + phraseId
Log.i(TAG, "recording name: " + name);
String gender = "";
int speakerGender = MetadataSession.getMetadataSession().getSpeakerGender();
if (speakerGender == RecordingMetadataLig.GENDER_MALE)
gender = "Male";
else if (speakerGender == RecordingMetadataLig.GENDER_FEMALE)
gender = "Female";
recordingLig = new RecordingLig(recordUUID, name, date,
AikumaSettings.getLatestVersion(),
AikumaSettings.getCurrentUserId(), MetadataSession.getMetadataSession().getRecordLanguage(),
MetadataSession.getMetadataSession().getMotherTongue(),
MetadataSession.getMetadataSession().getExtraLanguages(), speakerIds, deviceName, androidID,
null, null, sampleRate, duration,
recorder.getFormat(), recorder.getNumChannels(),
recorder.getBitsPerSample(), latitude, longitude,
MetadataSession.getMetadataSession().getRegionOrigin(), MetadataSession.getMetadataSession().getSpeakerName(),
MetadataSession.getMetadataSession().getSpeakerAge(), gender);
} else{
restoreMetaDataFromJson();
}
}
/**
* called when we want save a file.
* @return
*/
private boolean saveRecording() {
try {
recorder.stop();
} catch (MicException e) {
Log.e(TAG, "error when saving the recroding: " + e);
Toast.makeText(this, "An error occurred when saving the recording. Please try again.", Toast.LENGTH_LONG).show();
return false;
}
setRecordingLig();
try {
recordingLig.write();
String filename = recordingLig.getFile().getAbsolutePath();
FileUtils.copyFile(recordingLig.getFile(),
new File(filename.replace(".wav", "_" + imageId + ".wav")));
FileIO.delete(new File(filename));
FileUtils.copyFile(new File(filename.replace(".wav", "-metadata.json")),
new File(filename.replace(".wav", "_" + imageId + "-metadata.json")));
FileIO.delete(new File(filename.replace(".wav", "-metadata.json")));
recorder.release();
recorder = null;
} catch (IOException e) {
Log.e(TAG, "error when saving the recroding: " + e);
Toast.makeText(this, "An error occurred when saving the recording. Please try again.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
/**
* called when we want to save one record. Used when we touch newt button
*/
private void saveOneRecord() {
recordUUID = UUID.randomUUID();
try {
File f = new File(Recording.getNoSyncRecordingsPath(),
recordUUID.toString() + ".wav");
if (recorder != null) { recorder.release(); }
recorder = new Recorder(0, f, sampleRate);
Log.i(TAG, "recorder filename: " + recorder.getWriter().getFullFileName());
fragment.releasePlayer();
TextView tv2 = (TextView) findViewById(R.id.elicit_phrase_number);
tv2.setText(imageId + 1 + "");
progressBar.setProgress((int) (((float)imageId + 1.0)/(float)numberOfImages * 100));
} catch (MicException e) {
this.finish();
Toast.makeText(getApplicationContext(),
"Error setting up microphone.",
Toast.LENGTH_LONG).show();
}
}
// Pauses the recording.
private void pause() {
if (recording) {
recording = false;
ImageButton recordButton =
(ImageButton) findViewById(R.id.btn_record_elicit);
recordButton.setImageResource(R.drawable.record);
ImageButton nextButton = (ImageButton) findViewById(R.id.btn_next);
nextButton.setEnabled(true);
ImageButton validateButton = (ImageButton) findViewById(R.id.btn_validate);
validateButton.setEnabled(true);
try {
recorder.pause();
recorder.stop();
// the player can only be set when the file is closed (hence the recorder stopped)
// indeed, they both require a file descriptor (fd) on the same file;
// when i tried to set up the player while the recorder was still holding the fd,
// there was an error about the failure to set the fd; which i interpreted this way
fragment.releasePlayer();
SimplePlayer player = new SimplePlayer(new File(recorder.getWriter().getFullFileName()), sampleRate, true);
fragment.setPlayer(player);
} catch (MicException e) {
// Maybe make a recording metadata file that refers to the error so
// that the audio can be salvaged.
}
catch (IOException e) {
Log.e(TAG, "Could not start the fragment of the file "
+ new File(Recording.getNoSyncRecordingsPath(), recordUUID.toString() + ".wav")
+ " : " + e);
}
}
}
// Activates recording
private void record() {
if (!recording) {
recording = true;
ImageButton recordButton =
(ImageButton) findViewById(R.id.btn_record_elicit);
recordButton.setImageResource(R.drawable.pause);
ImageButton nextButton = (ImageButton) findViewById(R.id.btn_next);
nextButton.setEnabled(false);
ImageButton validateButton = (ImageButton) findViewById(R.id.btn_validate);
validateButton.setEnabled(false);
if (recorder != null) { recorder.release(); }
try {
File f = new File(Recording.getNoSyncRecordingsPath(),
"/" + recordUUID.toString() + ".wav");
recorder = new Recorder(0, f, sampleRate);
} catch (MicException e) {
this.finish();
Toast.makeText(getApplicationContext(),
"Error setting up microphone.",
Toast.LENGTH_LONG).show();
}
recorder.listen();
}
}
public void onNextClick(View v) {
if (saveRecording()) {
saveOneRecord();
} else {
Toast.makeText(this, "Going to next sentence...", Toast.LENGTH_LONG).show();
}
if (imageId < numberOfImages-1) {
imageId++;
loadImage();
}
if (imageId == numberOfImages-1)
v.setEnabled(false);
}