Get complete response logs in the logcat monitor? - android

The response coming from server is too long. So I am not able to see the complete response in the logcat monitor in android studio.
Is there any way to get the complete logcat of the response ?

For this, you should use debug points. You can get complete response and can see step by step execution of your code. For more you can go into the below website :
https://developer.android.com/studio/debug/index.html

Creating custom class for this. The important method for using it inside your code is splitAndLog by #pctroll.
public class Utils {
/**
* Divides a string into chunks of a given character size.
*
* #param text String text to be sliced
* #param sliceSize int Number of characters
* #return ArrayList<String> Chunks of strings
*/
public static ArrayList<String> splitString(String text, int sliceSize) {
ArrayList<String> textList = new ArrayList<String>();
String aux;
int left = -1, right = 0;
int charsLeft = text.length();
while (charsLeft != 0) {
left = right;
if (charsLeft >= sliceSize) {
right += sliceSize;
charsLeft -= sliceSize;
}
else {
right = text.length();
aux = text.substring(left, right);
charsLeft = 0;
}
aux = text.substring(left, right);
textList.add(aux);
}
return textList;
}
/**
* Divides a string into chunks.
*
* #param text String text to be sliced
* #return ArrayList<String>
*/
public static ArrayList<String> splitString(String text) {
return splitString(text, 80);
}
/**
* Divides the string into chunks for displaying them
* into the Eclipse's LogCat.
*
* #param text The text to be split and shown in LogCat
* #param tag The tag in which it will be shown.
*/
public static void splitAndLog(String tag, String text) {
ArrayList<String> messageList = Utils.splitString(text);
for (String message : messageList) {
Log.d(tag, message);
}
}
}

Related

How can i change the speaker label in ibm watson speech to text api in android?

Good Day!
I need help in developing my android app. is this possible to change the default name of speaker label to a custom one like a person name. i would like to create like this conversation as I example..
Jhon: Hi
Marie: Hello
Jhon: Good Day To you marie..
Marie:......
Please help i need help if is this possible to change the default name of speaker label i need your help
i created like this
private RecognizeOptions getRecognizeOptions(InputStream captureStream) {
return new RecognizeOptions.Builder()
.audio(captureStream)
.contentType(ContentType.OPUS.toString())
.model("en-US_BroadbandModel")
.interimResults(true)
.inactivityTimeout(2000)
.timestamps(true)
.speakerLabels(true)
.maxAlternatives(3)
.smartFormatting(true)
.timestamps(true)
.wordConfidence(true)
.build();
}
this is the method of .speakerLabels
public class SpeakerLabelsDiarization {
public static class RecoToken {
private Double startTime;
private Double endTime;
private Long speaker;
private String word;
private Boolean spLabelIsFinal;
/**
* Instantiates a new reco token.
*
* #param speechTimestamp the speech timestamp
*/
RecoToken(SpeechTimestamp speechTimestamp) {
startTime = speechTimestamp.getStartTime();
endTime = speechTimestamp.getEndTime();
word = speechTimestamp.getWord();
}
/**
* Instantiates a new reco token.
*
* #param speakerLabel the speaker label
*/
RecoToken(SpeakerLabelsResult speakerLabel) {
startTime = Double.valueOf(speakerLabel.getFrom());
endTime = Double.valueOf(speakerLabel.getTo());
speaker = speakerLabel.getSpeaker();
}
/**
* Update from.
*
* #param speechTimestamp the speech timestamp
*/
public void updateFrom(SpeechTimestamp speechTimestamp) {
word = speechTimestamp.getWord();
}
/**
* Update from.
*
* #param speakerLabel the speaker label
*/
public void updateFrom(SpeakerLabelsResult speakerLabel) {
speaker = speakerLabel.getSpeaker();
}
}
/**
* The Class Utterance.
*/
public static class Utterance {
private Integer speaker;
private String transcript = "";
/**
* Instantiates a new utterance.
*
* #param speaker the speaker
* #param transcript the transcript
*/
public Utterance(final Integer speaker, final String transcript) {
this.speaker = speaker;
this.transcript = transcript;
}
}
/**
* The Class RecoTokens.
*/
public static class RecoTokens {
private Map<Double, RecoToken> recoTokenMap;
/**
* Instantiates a new reco tokens.
*/
public RecoTokens() {
recoTokenMap = new LinkedHashMap<Double, RecoToken>();
}
/**
* Adds the.
*
* #param speechResults the speech results
*/
public void add(SpeechRecognitionResults speechResults) {
if (speechResults.getResults() != null)
for (int i = 0; i < speechResults.getResults().size(); i++) {
SpeechRecognitionResult transcript = speechResults.getResults().get(i);
if (transcript.isFinalResults()) {
SpeechRecognitionAlternative speechAlternative = transcript.getAlternatives().get(0);
for (int ts = 0; ts < speechAlternative.getTimestamps().size(); ts++) {
SpeechTimestamp speechTimestamp = speechAlternative.getTimestamps().get(ts);
add(speechTimestamp);
}
}
}
if (speechResults.getSpeakerLabels() != null)
for (int i = 0; i < speechResults.getSpeakerLabels().size(); i++) {
add(speechResults.getSpeakerLabels().get(i));
}
}
/**
* Adds the.
*
* #param speechTimestamp the speech timestamp
*/
public void add(SpeechTimestamp speechTimestamp) {
RecoToken recoToken = recoTokenMap.get(speechTimestamp.getStartTime());
if (recoToken == null) {
recoToken = new RecoToken(speechTimestamp);
recoTokenMap.put(speechTimestamp.getStartTime(), recoToken);
} else {
recoToken.updateFrom(speechTimestamp);
}
}
/**
* Adds the.
*
* #param speakerLabel the speaker label
*/
public void add(SpeakerLabelsResult speakerLabel) {
RecoToken recoToken = recoTokenMap.get(speakerLabel.getFrom());
if (recoToken == null) {
recoToken = new RecoToken(speakerLabel);
recoTokenMap.put(Double.valueOf(speakerLabel.getFrom()), recoToken);
} else {
recoToken.updateFrom(speakerLabel);
}
if (speakerLabel.isFinalResults()) {
markTokensBeforeAsFinal(speakerLabel.getFrom());
report();
cleanFinal();
}
}
private void markTokensBeforeAsFinal(Float from) {
Map<Double, RecoToken> recoTokenMap = new LinkedHashMap<>();
for (RecoToken rt : recoTokenMap.values()) {
if (rt.startTime <= from)
rt.spLabelIsFinal = true;
}
}
/**
* Report.
*/
public void report() {
List<Utterance> uttterances = new ArrayList<Utterance>();
Utterance currentUtterance = new Utterance(0, "");
for (RecoToken rt : recoTokenMap.values()) {
if (currentUtterance.speaker != Math.toIntExact(rt.speaker)) {
uttterances.add(currentUtterance);
currentUtterance = new Utterance(Math.toIntExact(rt.speaker), "");
}
currentUtterance.transcript = currentUtterance.transcript + rt.word + " ";
}
uttterances.add(currentUtterance);
String result = GsonSingleton.getGson().toJson(uttterances);
System.out.println(result);
}
private void cleanFinal() {
Set<Map.Entry<Double, RecoToken>> set = recoTokenMap.entrySet();
for (Map.Entry<Double, RecoToken> e : set) {
if (e.getValue().spLabelIsFinal) {
recoTokenMap.remove(e.getKey());
}
}
}
}
private static CountDownLatch lock = new CountDownLatch(1);
}
the output in that is like this`
speaker 0: Hi
speaker 1: Hello
speaker 0: Good Day To you marie..
speaker 1:......
and i would like to output like this
Jhon: Hi
Marie: Hello
Jhon: Good Day To you marie..
Marie:......
my question is. Is this possible to create like that in ibm watspon speech to text api because i read in their documentation their are not mentioning on how to change the labels i just want to clarify it if is this possible
There is nothing in the API nor the documentation to suggest that it is possible to modify the labels in the output using the service itself. https://cloud.ibm.com/docs/services/speech-to-text/output.html#speaker_labels

Tesseract ocr returns null string

I am building an OCR app for android and i use tesseract ocr engine. Somehow every time i use the engine on a photo it returns an empty text.
This is my code:
public String detectText(Bitmap bitmap) {
TessBaseAPI tessBaseAPI = new TessBaseAPI();
String mDataDir = setTessData();
tessBaseAPI.setDebug(true);
tessBaseAPI.init(mDataDir + File.separator, "eng");
tessBaseAPI.setImage(bitmap);
tessBaseAPI.setPageSegMode(TessBaseAPI.OEM_TESSERACT_ONLY);
String text = tessBaseAPI.getUTF8Text();
tessBaseAPI.end();
return text;
}
private String setTessData(){
String mDataDir = this.getExternalFilesDir("data").getAbsolutePath();
String mTrainedDataPath = mDataDir + File.separator + "tessdata";
String mLang = "eng";
// Checking if language file already exist inside data folder
File dir = new File(mTrainedDataPath);
if (!dir.exists()) {
if (!dir.mkdirs()) {
//showDialogFragment(SD_ERR_DIALOG, "sd_err_dialog");
} else {
}
}
if (!(new File(mTrainedDataPath + File.separator + mLang + ".traineddata")).exists()) {
// If English or Hebrew, we just copy the file from assets
if (mLang.equals("eng") || mLang.equals("heb")){
try {
AssetManager assetManager = context.getAssets();
InputStream in = assetManager.open(mLang + ".traineddata");
OutputStream out = new FileOutputStream(mTrainedDataPath + File.separator + mLang + ".traineddata");
copyFile(in, out);
//Toast.makeText(context, getString(R.string.selected_language) + " " + mLangArray[mLangID], Toast.LENGTH_SHORT).show();
//Log.v(TAG, "Copied " + mLang + " traineddata");
} catch (IOException e) {
//showDialogFragment(SD_ERR_DIALOG, "sd_err_dialog");
}
}
else{
// Checking if Network is available
if (!isNetworkAvailable(this)){
//showDialogFragment(NETWORK_ERR_DIALOG, "network_err_dialog");
}
else {
// Shows a dialog with File dimension. When user click on OK download starts. If he press Cancel revert to english language (like NETWORK ERROR)
//showDialogFragment(CONTINUE_DIALOG, "continue_dialog");
}
}
}
else {
//Toast.makeText(mThis, getString(R.string.selected_language) + " " + mLangArray[mLangID], Toast.LENGTH_SHORT).show();
}
return mDataDir;
}
I have debugged it many times and the bitmap is being transferred correctly to the detectText method. The language data files(tessdata) exists on the phone and the path to them is also correct.
Does anybody knows what the problem here?
You are using the OCR Engine Mode Enum value for setting the page segmentation in your setTessData() method.
setTessData() {
...
tessBaseAPI.setPageSegMode(TessBaseAPI.OEM_TESSERACT_ONLY);
}
Based on the type of image on which you are trying to detect the characters, setting an appropriate Page segmentation mode will help detect the characters.
For example :
tessBaseAPI.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO);
The various other Page segmentation values are present in TessBaseApi.java :
/** Page segmentation mode. */
public static final class PageSegMode {
/** Orientation and script detection only. */
public static final int PSM_OSD_ONLY = 0;
/** Automatic page segmentation with orientation and script detection. (OSD) */
public static final int PSM_AUTO_OSD = 1;
/** Fully automatic page segmentation, but no OSD, or OCR. */
public static final int PSM_AUTO_ONLY = 2;
/** Fully automatic page segmentation, but no OSD. */
public static final int PSM_AUTO = 3;
/** Assume a single column of text of variable sizes. */
public static final int PSM_SINGLE_COLUMN = 4;
/** Assume a single uniform block of vertically aligned text. */
public static final int PSM_SINGLE_BLOCK_VERT_TEXT = 5;
/** Assume a single uniform block of text. (Default.) */
public static final int PSM_SINGLE_BLOCK = 6;
/** Treat the image as a single text line. */
public static final int PSM_SINGLE_LINE = 7;
/** Treat the image as a single word. */
public static final int PSM_SINGLE_WORD = 8;
/** Treat the image as a single word in a circle. */
public static final int PSM_CIRCLE_WORD = 9;
/** Treat the image as a single character. */
public static final int PSM_SINGLE_CHAR = 10;
/** Find as much text as possible in no particular order. */
public static final int PSM_SPARSE_TEXT = 11;
/** Sparse text with orientation and script detection. */
public static final int PSM_SPARSE_TEXT_OSD = 12;
/** Number of enum entries. */
public static final int PSM_COUNT = 13;
}
You can experiment with different page segmentation enum values and see which gives the best result.

Android custom EditText(currency format)

I have custom EditText which will convert the input and also able to reverse it. However it will always make the input decimal, with 1 or 2 values behind the input. Right now I am making some calculation app, which need integer. How to make this custom EditText to just take integer input and output?
The code:
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class NumericEditText extends EditText {
private final char GROUPING_SEPARATOR = DecimalFormatSymbols.getInstance().getGroupingSeparator();
private final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
private final String LEADING_ZERO_FILTER_REGEX = "^0+(?!$)";
private String mDefaultText = null;
private String mPreviousText = "";
private String mNumberFilterRegex = "[^\\d\\" + DECIMAL_SEPARATOR + "]";
/**
* Interface to notify listeners when numeric value has been changed or cleared
*/
public interface NumericValueWatcher {
/**
* Fired when numeric value has been changed
* #param newValue new numeric value
*/
void onChanged(double newValue);
/**
* Fired when numeric value has been cleared (text field is empty)
*/
void onCleared();
}
private List<NumericValueWatcher> mNumericListeners = new ArrayList<NumericValueWatcher>();
private final TextWatcher mTextWatcher = new TextWatcher() {
private boolean validateLock = false;
#Override
public void afterTextChanged(Editable s) {
if (validateLock) {
return;
}
// valid decimal number should not have more than 2 decimal separators
if (StringUtils.countMatches(s.toString(), String.valueOf(DECIMAL_SEPARATOR)) > 1) {
validateLock = true;
setText(mPreviousText); // cancel change and revert to previous input
setSelection(mPreviousText.length());
validateLock = false;
return;
}
if (s.length() == 0) {
handleNumericValueCleared();
return;
}
setTextInternal(format(s.toString()));
setSelection(getText().length());
handleNumericValueChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// do nothing
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// do nothing
}
};
private void handleNumericValueCleared() {
mPreviousText = "";
for (NumericValueWatcher listener : mNumericListeners) {
listener.onCleared();
}
}
private void handleNumericValueChanged() {
mPreviousText = getText().toString();
for (NumericValueWatcher listener : mNumericListeners) {
listener.onChanged(getNumericValue());
}
}
public NumericEditText(Context context, AttributeSet attrs) {
super(context, attrs);
addTextChangedListener(mTextWatcher);
setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// disable moving cursor
setSelection(getText().length());
}
});
}
/**
* Add listener for numeric value changed events
* #param watcher listener to add
*/
public void addNumericValueChangedListener(NumericValueWatcher watcher) {
mNumericListeners.add(watcher);
}
/**
* Remove all listeners to numeric value changed events
*/
public void removeAllNumericValueChangedListeners() {
while (!mNumericListeners.isEmpty()) {
mNumericListeners.remove(0);
}
}
/**
* Set default numeric value and how it should be displayed, this value will be used if
* {#link #clear} is called
* #param defaultNumericValue numeric value
* #param defaultNumericFormat display format for numeric value
*/
public void setDefaultNumericValue(double defaultNumericValue, final String defaultNumericFormat) {
mDefaultText = String.format(defaultNumericFormat, defaultNumericValue);
setTextInternal(mDefaultText);
}
/**
* Clear text field and replace it with default value set in {#link #setDefaultNumericValue} if
* any
*/
public void clear() {
setTextInternal(mDefaultText != null ? mDefaultText : "");
if (mDefaultText != null) {
handleNumericValueChanged();
}
}
/**
* Return numeric value repesented by the text field
* #return numeric value or {#link Double.NaN} if not a number
*/
public double getNumericValue() {
String original = getText().toString().replaceAll(mNumberFilterRegex, "");
try {
return NumberFormat.getInstance().parse(original).doubleValue();
} catch (ParseException e) {
return Double.NaN;
}
}
/**
* Add grouping separators to string
* #param original original string, may already contains incorrect grouping separators
* #return string with correct grouping separators
*/
private String format(final String original) {
final String[] parts = original.split("\\" + DECIMAL_SEPARATOR, -1);
String number = parts[0] // since we split with limit -1 there will always be at least 1 part
.replaceAll(mNumberFilterRegex, "")
.replaceFirst(LEADING_ZERO_FILTER_REGEX, "");
// add grouping separators, need to reverse back and forth since Java regex does not support
// right to left matching
number = StringUtils.reverse(
StringUtils.reverse(number).replaceAll("(.{3})", "$1" + GROUPING_SEPARATOR));
// remove leading grouping separator if any
number = StringUtils.removeStart(number, String.valueOf(GROUPING_SEPARATOR));
// add fraction part if any
if (parts.length > 1) {
number += DECIMAL_SEPARATOR + parts[1];
}
return number;
}
/**
* Change display text without triggering numeric value changed
* #param text new text to apply
*/
private void setTextInternal(String text) {
removeTextChangedListener(mTextWatcher);
setText(text);
addTextChangedListener(mTextWatcher);
}
}
Example:
input 10000
it will be 10,000 in an instant,
input 10000.12
it will be 10,000.12
what I've tried:
int input2 = 0;
String text2 = etpersen2.getText().toString();
if (text2.length() > 0)
input2 = Integer.parseInt(text2);
String e = String.valueOf(input2);
etresult.setText("" + e);
Using Math.round() should round the float to the nearest whole number. It returns an int value so typecasting using (int) is redundant.
public class Test{
public static void main(String args[]){
double d = 100.675;
double e = 100.500;
float f = 100;
float g = 90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}

Automate File transfer to a PAIRED device in android using bluetooth

I'm a newbie in android programming. So, basically I was trying to automate a file transfer from my android phone(2.3.3) to a PAIRED laptop bluetooth...
I can send manually using share--bluetooth--search for paired device and then send it.
But I want to accomplish this automatically.
APP must only be on sender side. (Duh! receiver is laptop)
App code:
File myFile = new File(Environment.getExternalStorageDirectory()+"/mysdfile.txt");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){}
if(!mBluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
if(device.getName().equals("HARSHAR-HP")){
mmDevice = device;
mdeviceadd= device.getAddress();
Log.d(TAG, "found device");
break;
}else {
Log.d(TAG, "FAilure");
}
}
}
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI,Environment.getExternalStorageDirectory()+"/mysdfile.txt");
values.put(BluetoothShare.DESTINATION, mdeviceadd);
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI, values);
Log.d(TAG, "Till here ok");
BluetoothShare.java:
import android.provider.BaseColumns;
import android.net.Uri;
/**
* Exposes constants used to interact with the Bluetooth Share manager's content
* provider.
*/
public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {
}
/**
* The permission to access the Bluetooth Share Manager
*/
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";
/**
* The content:// URI for the data table in the provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://com.android.bluetooth.opp/btopp");
/**
* Broadcast Action: this is sent by the Bluetooth Share component to
* transfer complete. The request detail could be retrieved by app * as _ID
* is specified in the intent's data.
*/
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";
/**
* This is sent by the Bluetooth Share component to indicate there is an
* incoming file need user to confirm.
*/
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";
/**
* This is sent by the Bluetooth Share component to indicate there is an
* incoming file request timeout and need update UI.
*/
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";
/**
* The name of the column containing the URI of the file being
* sent/received.
*/
public static final String URI = "uri";
/**
* The name of the column containing the filename that the incoming file
* request recommends. When possible, the Bluetooth Share manager will
* attempt to use this filename, or a variation, as the actual name for the
* file.
*/
public static final String FILENAME_HINT = "hint";
/**
* The name of the column containing the filename where the shared file was
* actually stored.
*/
public static final String _DATA = "_data";
/**
* The name of the column containing the MIME type of the shared file.
*/
public static final String MIMETYPE = "mimetype";
/**
* The name of the column containing the direction (Inbound/Outbound) of the
* transfer. See the DIRECTION_* constants for a list of legal values.
*/
public static final String DIRECTION = "direction";
/**
* The name of the column containing Bluetooth Device Address that the
* transfer is associated with.
*/
public static final String DESTINATION = "destination";
/**
* The name of the column containing the flags that controls whether the
* transfer is displayed by the UI. See the VISIBILITY_* constants for a
* list of legal values.
*/
public static final String VISIBILITY = "visibility";
/**
* The name of the column containing the current user confirmation state of
* the transfer. Applications can write to this to confirm the transfer. the
* USER_CONFIRMATION_* constants for a list of legal values.
*/
public static final String USER_CONFIRMATION = "confirm";
/**
* The name of the column containing the current status of the transfer.
* Applications can read this to follow the progress of each download. See
* the STATUS_* constants for a list of legal values.
*/
public static final String STATUS = "status";
/**
* The name of the column containing the total size of the file being
* transferred.
*/
public static final String TOTAL_BYTES = "total_bytes";
/**
* The name of the column containing the size of the part of the file that
* has been transferred so far.
*/
public static final String CURRENT_BYTES = "current_bytes";
/**
* The name of the column containing the timestamp when the transfer is
* initialized.
*/
public static final String TIMESTAMP = "timestamp";
/**
* This transfer is outbound, e.g. share file to other device.
*/
public static final int DIRECTION_OUTBOUND = 0;
/**
* This transfer is inbound, e.g. receive file from other device.
*/
public static final int DIRECTION_INBOUND = 1;
/**
* This transfer is waiting for user confirmation.
*/
public static final int USER_CONFIRMATION_PENDING = 0;
/**
* This transfer is confirmed by user.
*/
public static final int USER_CONFIRMATION_CONFIRMED = 1;
/**
* This transfer is auto-confirmed per previous user confirmation.
*/
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;
/**
* This transfer is denied by user.
*/
public static final int USER_CONFIRMATION_DENIED = 3;
/**
* This transfer is timeout before user action.
*/
public static final int USER_CONFIRMATION_TIMEOUT = 4;
/**
* This transfer is visible and shows in the notifications while in progress
* and after completion.
*/
public static final int VISIBILITY_VISIBLE = 0;
/**
* This transfer doesn't show in the notifications.
*/
public static final int VISIBILITY_HIDDEN = 1;
/**
* Returns whether the status is informational (i.e. 1xx).
*/
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
/**
* Returns whether the transfer is suspended. (i.e. whether the transfer
* won't complete without some action from outside the transfer manager).
*/
public static boolean isStatusSuspended(int status) {
return (status == STATUS_PENDING);
}
/**
* Returns whether the status is a success (i.e. 2xx).
*/
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
/**
* Returns whether the status is an error (i.e. 4xx or 5xx).
*/
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
/**
* Returns whether the status is a client error (i.e. 4xx).
*/
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
/**
* Returns whether the status is a server error (i.e. 5xx).
*/
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
/**
* Returns whether the transfer has completed (either with success or
* error).
*/
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300) || (status >= 400 && status < 600);
}
/**
* This transfer hasn't stated yet
*/
public static final int STATUS_PENDING = 190;
/**
* This transfer has started
*/
public static final int STATUS_RUNNING = 192;
/**
* This transfer has successfully completed. Warning: there might be other
* status values that indicate success in the future. Use isSucccess() to
* capture the entire category.
*/
public static final int STATUS_SUCCESS = 200;
/**
* This request couldn't be parsed. This is also used when processing
* requests with unknown/unsupported URI schemes.
*/
public static final int STATUS_BAD_REQUEST = 400;
/**
* This transfer is forbidden by target device.
*/
public static final int STATUS_FORBIDDEN = 403;
/**
* This transfer can't be performed because the content cannot be handled.
*/
public static final int STATUS_NOT_ACCEPTABLE = 406;
/**
* This transfer cannot be performed because the length cannot be determined
* accurately. This is the code for the HTTP error "Length Required", which
* is typically used when making requests that require a content length but
* don't have one, and it is also used in the client when a response is
* received whose length cannot be determined accurately (therefore making
* it impossible to know when a transfer completes).
*/
public static final int STATUS_LENGTH_REQUIRED = 411;
/**
* This transfer was interrupted and cannot be resumed. This is the code for
* the OBEX error "Precondition Failed", and it is also used in situations
* where the client doesn't have an ETag at all.
*/
public static final int STATUS_PRECONDITION_FAILED = 412;
/**
* This transfer was canceled
*/
public static final int STATUS_CANCELED = 490;
/**
* This transfer has completed with an error. Warning: there will be other
* status values that indicate errors in the future. Use isStatusError() to
* capture the entire category.
*/
public static final int STATUS_UNKNOWN_ERROR = 491;
/**
* This transfer couldn't be completed because of a storage issue.
* Typically, that's because the file system is missing or full.
*/
public static final int STATUS_FILE_ERROR = 492;
/**
* This transfer couldn't be completed because of no sdcard.
*/
public static final int STATUS_ERROR_NO_SDCARD = 493;
/**
* This transfer couldn't be completed because of sdcard full.
*/
public static final int STATUS_ERROR_SDCARD_FULL = 494;
/**
* This transfer couldn't be completed because of an unspecified un-handled
* OBEX code.
*/
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;
/**
* This transfer couldn't be completed because of an error receiving or
* processing data at the OBEX level.
*/
public static final int STATUS_OBEX_DATA_ERROR = 496;
/**
* This transfer couldn't be completed because of an error when establishing
* connection.
*/
public static final int STATUS_CONNECTION_ERROR = 497;
}
NO error in code... but nothing happens.
file is not transfered.. please someone help me fix the code.. DOnt ask me to see SAMPLE EXAMPLE, Didnt understand how to send file through it.
I'm afraid that way of transferring files is not valid in Android 4+.
Instead, you can use this piece of code, though it will not transfer automatically the file, it prompts the user to select the destination. I don't think it's possible to send files without user authorization anymore, it's a huge security flaw in my opinion.
public void sendFile(String fileName){
Log.d(TAG, "Sending file...");
File dir = Environment.getExternalStorageDirectory();
File manualFile = new File(dir, "/" + fileName);
Uri uri = Uri.fromFile(manualFile);
String type = "application/pdf";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType(type);
sharingIntent.setClassName("com.android.bluetooth", "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(sharingIntent);
}

How to convert the WAV/OGG file to FLAC file in Android?

EDIT: Incorporated the changed uv001's answer.
I can only find that ICS 4.0 support decoding of FLAC, but encode. I need some encoder to convert wav to flac, but currenty I can't find it. I find there is a jFlac avaible , but I don't know how to use this library, just simply convert the files.
Could anyone give me a hand on it?
Today, I just some idea by myself, with using the JavaFlacEncoder.
and it works for certain bitrates of WAV.
I changed the value into a hard coding value in which it is working now.
/*
* Copyright (C) 2010 Preston Lacey http://javaflacencoder.sourceforge.net/
* All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package javaFlacEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* FLAC_FileEncoder is a class to encode an input wav File to an output Flac
* file. It allows the EncodingConfiguration to be set only once, prior to
* encoding the entire File.
*
* #author Preston Lacey
* #author Bo Tan (Temple)
*/
public class FLAC_FileEncoder {
/** Maximum number of bytes to read from file at once */
private static final int MAX_READ = 16384;
/** Status enum for encode result */
public enum Status {
/** Unknown State. */
UNKNOWN,
/** Everything went well */
FULL_ENCODE,
/** Something unspecified went wrong...*/
GENERAL_ERROR,
/** internal error is something that went haywire that was discovered
* due to internal sanity checks. A problem in API. */
INTERNAL_ERROR,
/** File given was not able to be read */
UNSUPPORTED_FILE,
/** Generic file IO Error */
FILE_IO_ERROR,
/** Sample size unsupported */
UNSUPPORTED_SAMPLE_SIZE,
/** Error with output file */
OUTPUT_FILE_ERROR,
/** No errors found. */
OK
}
FLACEncoder flac = null;
StreamConfiguration sc = null;
EncodingConfiguration ec = null;
File outFile = null;
int lastTotalSamples = 0;
boolean useThreads;
/**
* Constructor creates a FLAC_FileEncoder object with default
* StreamConfiguration configuration and default EncodingConfiguration.
* Thread use defaults to true.
*/
public FLAC_FileEncoder() {
flac = new FLACEncoder();
sc = new StreamConfiguration();
ec = new EncodingConfiguration();
useThreads = true;
}
/**
* Specify whether to use multiple threads or not.
* #param val true to use threads, false otherwise.
*/
public void useThreads(boolean val) {
useThreads = val;
}
private void adjustConfigurations(){//(AudioFormat format) {
int sampleRate = 16000;//(int)format.getSampleRate();
int sampleSize = 16; //(int)format.getSampleSizeInBits();
int channels =1;// (int)format.getChannels();
//int blockSize = sc.getMaxBlockSize();
/*sc = new StreamConfiguration(channels, blockSize, blockSize,
sampleRate, sampleSize);*/
sc.setSampleRate(sampleRate);
sc.setBitsPerSample(sampleSize);
sc.setChannelCount(channels);
}
/**
* Set the stream configuration for this encoder to use. Note that the audio
* characteristics(number of channels, sample rate, and sample size), will
* be set to match the input file at encode time, so needn't be set in the
* given StreamConfiguration object.
*
* #param config StreamConfiguration to use for encoding.
*/
public void setStreamConfig(StreamConfiguration config) {sc = config; }
/**
* Set the EncodingConfiguration to use for encoding.
* #param config EncodingConfiguration to use.
*/
public void setEncodingConfig(EncodingConfiguration config){ec = config;}
private Status openStream() {
Status status = Status.OK;
boolean result = flac.setStreamConfiguration(sc);
result = result & flac.setEncodingConfiguration(ec);
if( !result)
status = Status.INTERNAL_ERROR;
else {
FLACFileOutputStream fout = null;
try {
fout = new FLACFileOutputStream(outFile.getPath());
} catch(IOException e) {
status = Status.OUTPUT_FILE_ERROR;
e.printStackTrace();
}
if( status == Status.OK) {
flac.setOutputStream(fout);
try {
flac.openFLACStream();
}catch(IOException e) {
status = Status.INTERNAL_ERROR;
}
}
else
status = Status.OUTPUT_FILE_ERROR;
}
return status;
}
/**
* Encode the given input wav file to an output file.
*
* #param inputFile Input wav file to encode.
* #param outputFile Output file to write FLAC stream to. If file exists, it
* will be overwritten without prompting.
*
* #return Status flag for encode
*/
public Status encode(File inputFile, File outputFile) {
Status status = Status.FULL_ENCODE;
this.outFile = outputFile;
//take file and initial configuration.
//open file
// AudioInputStream sin = null;
// AudioFormat format = null;
// //File inputFile = new File("encoderTest.wav");
// try {
// sin = AudioSystem.getAudioInputStream(inputFile);
// }catch(IOException e) {
// status = Status.FILE_IO_ERROR;
// }catch (UnsupportedAudioFileException e) {
// status = Status.UNSUPPORTED_FILE;
// }finally {
// if(status != Status.FULL_ENCODE)
// return status;
// }
FileInputStream sin=null;
try {
sin = new FileInputStream(inputFile);
} catch (FileNotFoundException e1) {
status = Status.FILE_IO_ERROR;
e1.printStackTrace();
}finally {
if (status != Status.FULL_ENCODE)
return status;
}
try {
// format = sin.getFormat();
//sanitize and optimize configurations
adjustConfigurations(); //adjustConfigurations(format);
//open stream
openStream();
int frameSize = 2;//format.getFrameSize();
int sampleSize = 16;//format.getSampleSizeInBits();
int bytesPerSample = sampleSize/8;
if(sampleSize %8 != 0) {
//end processing now
Exception newEx = new Exception(Status.UNSUPPORTED_SAMPLE_SIZE.name());
throw newEx;
}
int channels =1;// format.getChannels();
boolean bigEndian =false;// format.isBigEndian();
byte[] samplesIn = new byte[(int)MAX_READ];
int samplesRead;
int framesRead;
int[] sampleData = new int[MAX_READ*channels/frameSize];
int blockSize = sc.getMaxBlockSize();
int unencodedSamples = 0;
int totalSamples = 0;
while((samplesRead = sin.read(samplesIn, 0, MAX_READ)) != -1) {
//System.err.println("Read: " + read);
framesRead = samplesRead/(frameSize);
if(bigEndian) {
for(int i = 0; i < framesRead*channels; i++) {
int lower8Mask = 255;
int temp = 0;
int totalTemp = 0;
for(int x = bytesPerSample-1; x >= 0; x++) {
int upShift = 8*x;
if(x == 0)//don't mask...we want sign
temp = ((samplesIn[bytesPerSample*i+x]) << upShift);
else
temp = ((samplesIn[bytesPerSample*i+x] & lower8Mask) << upShift);
totalTemp = totalTemp | temp;
}
sampleData[i] = totalTemp;
}
}
else {
for(int i = 0; i < framesRead*channels; i++) {
int lower8Mask = 255;
int temp = 0;
int totalTemp = 0;
for(int x = 0; x < bytesPerSample; x++) {
int upShift = 8*x;
if(x == bytesPerSample-1)//don't mask...we want sign
temp = ((samplesIn[bytesPerSample*i+x]) << upShift);
else
temp = ((samplesIn[bytesPerSample*i+x] & lower8Mask) << upShift);
totalTemp = totalTemp | temp;
}
sampleData[i] = totalTemp;
}
}
if(framesRead > 0) {
flac.addSamples(sampleData, framesRead);
unencodedSamples += framesRead;
}
//if(unencodedSamples > blockSize*100) {
if(useThreads)//Thread.yield();//
unencodedSamples -= flac.t_encodeSamples(unencodedSamples, false, flac.getThreadCount());
else
unencodedSamples -= flac.encodeSamples(unencodedSamples, false);
totalSamples += unencodedSamples;
//unencodedSamples = 0;
//}
//System.err.println("read : "+ samplesRead);
}
totalSamples += unencodedSamples;
if(useThreads)
unencodedSamples -= flac.t_encodeSamples(unencodedSamples, true, flac.getThreadCount());
else
unencodedSamples -= flac.encodeSamples(unencodedSamples, true);
//unencodedSamples = 0;
lastTotalSamples = totalSamples;
}
catch(IOException e) {
status = Status.FILE_IO_ERROR;
}
catch(Exception e) {
status = Status.GENERAL_ERROR;
String message = e.getMessage();
if(message == null) {
e.printStackTrace();
}
else if(message.equals(Status.UNSUPPORTED_SAMPLE_SIZE.name()))
status = Status.UNSUPPORTED_SAMPLE_SIZE;
}
//System.err.print("LastTotalSamples: "+lastTotalSamples);
return status;
}
/**
* Get the total number of samples encoded in last encode. This is here
* primarily for use as a sanity check during debugging.
*
* #return Total number of samples encoded in last encode attempt.
*/
public int getLastTotalSamplesEncoded() {
return this.lastTotalSamples;
}
}
Temple, Thanks for the post and the response with the attached code for FLAC conversion. It works as you described with one minor issue.
The FLACFileOutputStream (fout) and the FileInputStream (sin) are not closed at the end of the function. Please update your post/code so others can benefit as well.
finally {
try {
if (sin != null) sin.close();
if (fout != null) fout.close();
} catch (IOException e) {}
}
PS: FLACFileOutputStream fout will need to be promoted to a class variable for this to work.
Change the following line in your code
unencodedSamples -= flac.t_encodeSamples(unencodedSamples, true);
to
unencodedSamples -= flac.t_encodeSamples(unencodedSamples, true,flac.getThreadCount());

Categories

Resources