Override Cordova Log - java

I need to override the Log in Cordova Plugin because the code I'm using has some other functions i.e. Log.info which are causing a load of errors
In the code I'm using they override as such
public class GridActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize YiCameraPlatform
try {
Platform.initialize(new Logger() {
#Override
public void verbose(String message) {
Log.v("YiCameraPlatform", message);
}
#Override
public void info(String message) {
Log.i("YiCameraPlatform", message);
}
#Override
public void warning(String message) {
Log.w("YiCameraPlatform", message);
}
#Override
public void error(String message) {
Log.e("YiCameraPlatform", message);
}
});
} catch (Exception ex) {
}
I need to do something similar in the plugin initialiser
public class XiaomiYiCordovaPlugin extends CordovaPlugin {
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Can anyone let me know how to do this?
I'm trying things such as
Log = new Logger() {
#Override
public void verbose(String message) {
Log.v("YiCameraPlatform", message);
}
#Override
public void info(String message) {
Log.i("YiCameraPlatform", message);
}
#Override
public void warning(String message) {
Log.w("YiCameraPlatform", message);
}
#Override
public void error(String message) {
Log.e("YiCameraPlatform", message);
}
};
To no avail..

Related

Is there a way to share async code between classes in java (Android)?

Let's say I have two classes A and B.
public class myClassA {
private void asyncMethodA(String url){
Observable.fromCallable((Callable<Void>) () -> null //common part of the code
).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Void>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onNext(#NonNull Void aVoid) {
someACode();
//This part is different for each class
}
#Override
public void onError(#NonNull Throwable e) {
}
#Override
public void onComplete() {
}
});
}
}
public class myClassB {
private void asyncMethodB(String url){
Observable.fromCallable((Callable<Void>) () -> null //common part of the code
).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Void>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onNext(#NonNull Void aVoid) {
someBCode();
//This part is different for each class
}
#Override
public void onError(#NonNull Throwable e) {
}
#Override
public void onComplete() {
}
});
}
}
Is it possible to have some sort of code that will help me not repeat the common part for each individual class? If so how do I implement it? It is necessary that the code will be asynchronous, so it won't lock the UI.

Android Nearby Connections cannot connect to device. Always returns 8011

I am trying to use Google Nearby Connections API to connect two Android devices to exchange data but no success.
The devices can found eachother none of them can connect to the other. It always fails at onConnectionInitiated() with
STATUS_ENDPOINT_UNKNOWN when I try to accept the connection.
I tried it with Strategy.P2P_POINT_TO_POINT Strategy.CLUSTER and Strategy.STAR but I get the same result.
Anyone can help me what do I miss?
Both devices are physical and running on Android 9.0
This is the code:
public static ConnectionLifecycleCallback connectionLifecycleCallback;
public static EndpointDiscoveryCallback endpointDiscoveryCallback;
public static PayloadCallback payloadCallback;
public static String SERVICE_ID;
public Context ctx;
public static Strategy STRATEGY;
public NearbyHandler(Context ctx,Strategy STRATEGY){
this.ctx = ctx;
this.STRATEGY = STRATEGY;
SERVICE_ID = ctx.getPackageName();
payloadCallback = new PayloadCallback() {
#Override
public void onPayloadReceived(#NonNull String s, #NonNull Payload payload) {
Log.d("NEARBY_", "PAYLOAD RECEIVED " + s);
}
#Override
public void onPayloadTransferUpdate(#NonNull String s, #NonNull PayloadTransferUpdate payloadTransferUpdate) {
Log.d("NEARBY_", "PAYLOAD TRANSFER UPDATE " + s);
}
};
connectionLifecycleCallback = new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String s, #NonNull ConnectionInfo connectionInfo) {
Nearby.getConnectionsClient(ctx)
.acceptConnection(s, payloadCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_", "SUCCESSFULLY CONNECTED");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
#Override
public void onConnectionResult(#NonNull String s, #NonNull ConnectionResolution connectionResolution) {
switch (connectionResolution.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
break;
case ConnectionsStatusCodes.STATUS_ERROR:
break;
}
}
#Override
public void onDisconnected(#NonNull String s) {
Log.d("NEARBY_", "DISCONNECTED " + s);
}
};
endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(#NonNull String s, #NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
Nearby.getConnectionsClient(ctx)
.requestConnection(
s,
ctx.getPackageName(),
connectionLifecycleCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_", "ENDPOINT CONNECTED");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("NEARBY_", "FAILED TO CONNECT ENDPOINT " + e.getMessage());
e.printStackTrace();
}
});
}
#Override
public void onEndpointLost(#NonNull String s) {
Log.d("NEARBY_", "ENDPOINT LOST: " + s);
}
};
}
public void startDiscovering() {
Nearby.getConnectionsClient(ctx)
.startDiscovery(
SERVICE_ID,
endpointDiscoveryCallback,
new DiscoveryOptions.Builder()
.setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_DISCOVERER_", "onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
public void startAdvertising() {
Nearby.getConnectionsClient(ctx)
.startAdvertising(
Build.MODEL,
SERVICE_ID,
connectionLifecycleCallback,
new AdvertisingOptions.Builder()
.setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
}
NearbyHandler nearby = new NearbyHandler(getApplicationContext(), Strategy.P2P_POINT_TO_POINT);
if (IS_DEVICE_A) {
nearby.startAdvertising();
} else {
nearby.startDiscovering();
}
Update: Google's walkietalkie demo app works fine on both phones.
Finally I've managed to get it working but not sure about the problem.
I managed the connection lifecycle a bit different way than in the API Docs.
So I created a private helper class
class Endpoint {
#NonNull
private final String id;
#NonNull
private final String name;
public Endpoint(#NonNull String id, #NonNull String name) {
this.id = id;
this.name = name;
}
#NonNull
public String getId() {
return id;
}
#NonNull
public String getName() {
return name;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Endpoint) {
Endpoint other = (Endpoint) obj;
return id.equals(other.id);
}
return false;
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return String.format("Endpoint{id=%s, name=%s}", id, name);
}
}
The ConnectionLifecycleCallback() and EndpointDiscoveryCallback() should look like this:
endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(#NonNull String s, #NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
Endpoint endpoint = new Endpoint(s, discoveredEndpointInfo.getEndpointName());
ConnectionsClient c = Nearby.getConnectionsClient(ctx);
c.requestConnection(endpoint.getName(), endpoint.getId(), connectionLifecycleCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
#Override
public void onSuccess(Void aVoid) {}
});
}
#Override
public void onEndpointLost(#NonNull String s) {}
};
connectionLifecycleCallback = new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String s, #NonNull ConnectionInfo connectionInfo) {
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
Endpoint endpoint = new Endpoint(s, connectionInfo.getEndpointName());
ConnectionsClient c = Nearby.getConnectionsClient(ctx);
c.acceptConnection(endpoint.getId(), payloadCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
#Override
public void onSuccess(Void aVoid) {}
});
}
#Override
public void onConnectionResult(#NonNull String s, #NonNull ConnectionResolution connectionResolution) {
switch (connectionResolution.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
// The connection was rejected by one or both sides.
break;
case ConnectionsStatusCodes.STATUS_ERROR:
// The connection broke before it was able to be accepted.
break;
}
}
#Override
public void onDisconnected(#NonNull String s) {}
};

MQTT send message from main thread

I have simple MQTT subscriber implemented in MqttHelper class that works fine and receives subscriptions. But how I should deal when I need to send message to server from main program. I have method publish that works fine from IMqttActionListener but how to send text from main program on button pressed event?
package com.kkk.mqtt.helpers;
import android.content.Context;
import android.util.Log;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.io.UnsupportedEncodingException;
public class MqttHelper {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "tcp://tailor.cloudmqtt.com:16424";
final String clientId = "ExampleAndroidClient";
public final String subscriptionTopic = "sensor";
final String username = "xxx";
final String password = "yyy";
public MqttHelper(Context context){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallbackExtended callback) {
mqttAndroidClient.setCallback(callback);
}
public void publish(String topic, String info)
{
byte[] encodedInfo = new byte[0];
try {
encodedInfo = info.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedInfo);
mqttAndroidClient.publish(topic, message);
Log.e ("Mqtt", "publish done");
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
Log.e ("Mqtt", e.getMessage());
}catch (Exception e) {
Log.e ("Mqtt", "general exception "+e.getMessage());
}
}
private void connect(){
Log.w("Mqtt", "connect start " );
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener()
{
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt", "onSuccess " );
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic();
publish(MqttHelper.this.subscriptionTopic,"information");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt","Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
}
Code that starts MQTT subscriber:
private void startMqtt() {
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.setCallback(new MqttCallbackExtended()
{
#Override
public void connectComplete(boolean b, String s) {
Log.w("Mqtt", "Connect complete"+ s );
}
#Override
public void connectionLost(Throwable throwable) {
Log.w("Mqtt", "Connection lost" );
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
dataReceived.setText(mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.w("Mqtt", "Delivery complete" );
}
});
Log.w("Mqtt", "will publish");
}
Paho does not run on the UI thread, but it may asynchronously call back to the UI thread.
Just let an Activity or Fragment implement the MqttCallbackExtended interface:
public class SomeActivity extends AppCompatActivity implements MqttCallbackExtended {
...
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.d("Mqtt", "Connect complete > " + serverURI);
}
#Override
public void connectionLost(Throwable cause) {
Log.d("Mqtt", "Connection lost");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d("Mqtt", "Received > " + topic + " > " + message.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d("Mqtt", "Delivery complete");
}
}
And construct the MqttHelper with SomeActivity as it's MqttCallbackExtended listener:
public MqttHelper(Context context, MqttCallbackExtended listener) {
this.mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
this.mqttAndroidClient.setCallback(listener);
}
For example:
this.mqttHelper = new MqttHelper(this);
this.mqttHelper.setCallback(this);
this.mqttHelper.publish("Java", "SomeActivity will handle the callbacks.");
Handling these in Application is problematic, because Application has no UI and it's Context has no Theme. But for classes extending Activity, Fragment, DialogFragment, RecyclerView.Adapter, etc. it makes senses to implement the callback interface, when wanting to interact with their UI.
For reference, MqttCallbackExtended extends MqttCallback.
Another Solution:
Create a MQTTService class that extends android.app.Service.
Android Service class works in the main thread. So if you want to use another thread, you can use MqttAsyncClient simply.
You will receive messages from the broker in another thread automatically (not main thread) in messageArrived() using callback method.
Pass Data/command from the application UI (Activity-Fragment,...) to the MQTTService by EventBus library simply.
Again use the EventBus in the messageArrived() callback method to pass the received data from the broker to the desired section of your application.
Please note that in this step if your destination is an application UI, you have to use #Subscribe(threadMode = ThreadMode.MAIN) in the destination to get data in the main thread.
Sample Code:
public class MQTTService extends Service {
private MqttAsyncClient mqttClient;
private String serverURI;
#Override
public void onCreate() {
//do your initialization here
serverURI = "tcp://yourBrokerUrlOrIP:yourBrokerPort";
EventBus.getDefault().register(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
init();
connect();
}
private void init() {
mqttClient = new MqttAsyncClient(serverURI, yourClientId, new MemoryPersistence())
mqttClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
//now you will receive messages from the broker in another thread automatically (not UI Thread).
//You can do your logic here. for example pass the received data to the different sections of the application:
EventBus.getDefault().post(new YourPOJO(topic, message, ...));
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
}
private MqttConnectOptions getOptions(){
MqttConnectOptions options = new MqttConnectOptions();
options.setKeepAliveInterval(...);
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setAutomaticReconnect(true);
options.setCleanSession(false);
options.setUserName(...);
options.setPassword(...);
//options.setWill(...);
//your other configurations
return options;
}
private void connect() {
try {
IMqttToken token = mqttClient.connect(getOptions(), null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
//do works after successful connection
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
mqttClient.close();
mqttClient.disconnect();
}
//this method receives your command from the different application sections
//you can simply create different "MqttCommandPOJO" classes for different purposes
#Subscribe
public void receiveFromApp1(MqttCommandPOJO1 pojo1) {
//do your logic(1). For example:
//publish or subscribe something to the broker (QOS=1 is a good choice).
}
#Subscribe
public void receiveFromApp2(MqttCommandPOJO2 pojo2) {
//do your logic(2). For example:
//publish or subscribe something to the broker (QOS=1 is a good choice).
}
}
Now You can simply receive the data passed from the MQTTService in every section of your application.
For example:
public class MainActivity extends AppCompatActivity {
...
#Subscribe(threadMode = ThreadMode.MAIN)
public void receiveFromMQTTService(YourPojo pojo){
//Do your logic. For example update the UI.
}
}
Another links:
General instructions
Best wishes

RecogniseListener stops at onReadyForSpeech

RecogniseListener works fine when there's continuous talk, but whenever there are 5-10seconds of silence, the listener's onReadyForSpeech() method is called, but onBegginingOfSpeech() is never called.
Here's my listener:
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
startRecognising();
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
adapter.add(new MessageData(MessageData.TYPE_VOICE, recognisedText.getText().toString()), 0);
recyclerView.scrollToPosition(0);
recognisedText.setText("");
}
#Override
public void onPartialResults(Bundle partialResults) {
ArrayList data = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
recognisedText.setText(word);
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
The startRecognising() method:
private void startRecognising(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000000);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
sr.startListening(intent);
}
By the way, are there any free alternatives that can recognise speech in real-time continuously?

java.io.IOException: Error running exec() Working Directory: null Environment: null

I am using WritingMinds/ffmpeg-android-java in application.
here is my code
loadFFmpeg();
String cmd="ffmpeg -i /storage/emulated/0/media/audio/a.mp3 -i /storage/emulated/0/recording.3gp -filter_complex \"[0:a][1:a]amerge=inputs=2[aout]\" -map \"[aout]\" " + outputFile;
executeFFmpeg(cmd.split(" "));
and
private void loadFFmpeg() {
FFmpeg ffmpeg = FFmpeg.getInstance(MainActivity.this.getApplicationContext());
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onFailure() {}
#Override
public void onSuccess() {}
#Override
public void onFinish() {}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
}
}
private void executeFFmpeg(String[] cmd)
{
/*String workFolder = getApplicationContext().getFilesDir() + "/ffmpeg";
String environment = Environment.getExternalStorageDirectory().getAbsolutePath();
Map<String, String> map = new HashMap<String, String>();
map.put("Working Directory", workFolder);
map.put("Environment",environment);*/
FFmpeg ffmpeg = FFmpeg.getInstance(MainActivity.this.getApplicationContext());
try {
// to execute "ffmpeg -version" command you just need to pass "-version"
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onProgress(String message) {}
#Override
public void onFailure(String message) {}
#Override
public void onSuccess(String message) {}
#Override
public void onFinish() {
stop.setEnabled(false);
play.setEnabled(true);
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// Handle if FFmpeg is already running
}
}
but I am getting following error
6784-6962/com.flipartstudio.playandrecord E/FFmpeg: Exception while trying to run: [Ljava.lang.String;#41803270
java.io.IOException: Error running exec(). Command: [/data/data/com.flipartstudio.playandrecord/files/ffmpeg, /system/bin/ls, -l, /data/data/com.example.foo/files/ffmpeg] Working Directory: null Environment: null
at java.lang.ProcessManager.exec(ProcessManager.java:211)
at java.lang.Runtime.exec(Runtime.java:168)
at java.lang.Runtime.exec(Runtime.java:123)
at com.github.hiteshsondhi88.libffmpeg.ShellCommand.run(ShellCommand.java:10)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:38)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:10)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.io.IOException: No such file or directory
at java.lang.ProcessManager.exec(Native Method)
at java.lang.ProcessManager.exec(ProcessManager.java:209)
at java.lang.Runtime.exec(Runtime.java:168) 
at java.lang.Runtime.exec(Runtime.java:123) 
at com.github.hiteshsondhi88.libffmpeg.ShellCommand.run(ShellCommand.java:10) 
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:38) 
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:10) 
at android.os.AsyncTask$2.call(AsyncTask.java:287) 
at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
at java.lang.Thread.run(Thread.java:856) 
I have also added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
your problem is that you declear FFmpeg once in loadFFmpeg() method and once in executeFFmpeg() . so in executeFFmpeg() your FFmpeg isn't loaded.
Solution :
your code should be like this :
public class Main extends Activity{
FFmpeg ffmpeg;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
loadFFmpeg();
String cmd="ffmpeg -i /storage/emulated/0/media/audio/a.mp3 -i /storage /emulated/0/recording.3gp -filter_complex \"[0:a][1:a]amerge=inputs=2[aout]\" -map \"[aout]\" " + outputFile;
executeFFmpeg(cmd.split(" "));
}
private void loadFFmpeg() {
ffmpeg = FFmpeg.getInstance(context);
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onFailure() {}
#Override
public void onSuccess() {}
#Override
public void onFinish() {}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
}
}
private void executeFFmpeg(String[] cmd)
{
try {
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onProgress(String message) {}
#Override
public void onFailure(String message) {}
#Override
public void onSuccess(String message) {}
#Override
public void onFinish() {
stop.setEnabled(false);
play.setEnabled(true);
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// Handle if FFmpeg is already running
}
}
}
Try this:
public class MainActivity extends Activity{
FFmpeg ffmpeg;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
loadFFmpeg();
String cmd="-i /storage/emulated/0/media/audio/a.mp3 -i /storage /emulated/0/recording.3gp -filter_complex \"[0:a][1:a]amerge=inputs=2[aout]\" -map \"[aout]\" " + outputFile;
executeFFmpeg(cmd.split(" "));
}
private void loadFFmpeg() {
ffmpeg = FFmpeg.getInstance(context);
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onFailure() {}
#Override
public void onSuccess() {}
#Override
public void onFinish() {}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
}
}
private void executeFFmpeg(String[] cmd)
{
try {
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onProgress(String message) {}
#Override
public void onFailure(String message) {}
#Override
public void onSuccess(String message) {}
#Override
public void onFinish() {
stop.setEnabled(false);
play.setEnabled(true);
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// Handle if FFmpeg is already running
}
}
}
Reason:
ffmpeg.loadBinary is Async. It returns immediately but the task doesn't complete at that time.
Solution:
You should put your code in onSuccess() of ffmpeg.loadBinary like this:
ffmpeg = FFmpeg.getInstance(context);
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
#Override
public void onStart() {}
#Override
public void onFailure() {}
#Override
public void onSuccess() {
String cmd="ffmpeg -i /storage/emulated/0/media/audio/a.mp3 -i /storage/emulated/0/recording.3gp -filter_complex \"[0:a][1:a]amerge=inputs=2[aout]\" -map \"[aout]\" " + outputFile;
executeFFmpeg(cmd.split(" "));
}
#Override
public void onFinish() {}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
}

Categories