Not able to get audio input for simple microphone app - java

I am in the process of learning out to use libpd with Android and have ran into a problem. I wanted to see if I could get a simple microphone app working. Just an ~adc -> bpfilter -> *2 -> ~dac. I verified that the patched worked with Pure Data and MobMuPlat.
I wrote over the example program "Circle of Fifths" to make sure libpd was included properly. When I modified it using a tutorial to run my own patch, I was unable to get input from the phone's microphone. The following line seemed to be the issue.
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
If I have the input channels to 0, the app will open but obviously no sound will come out.This is unless I change the patch to just play a tone and set inpch to 0. When the input channels are set inpch to 1,2, or AudioParameters.suggestInputChannels();the application will not open.
I have also tried small sample rates but I had the same issue. Any ideas?
Here is the full main activity:
/**
*
* #author Peter Brinkmann (peter.brinkmann#gmail.com)
*
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
*/
package org.puredata.android.fifths;
import java.io.File;
import java.io.IOException;
import org.puredata.android.io.AudioParameters;
import org.puredata.android.io.PdAudio;
import org.puredata.android.utils.PdUiDispatcher;
import org.puredata.core.PdBase;
import org.puredata.core.utils.IoUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CircleOfFifths extends Activity {
private static final String TAG = "GuitarTuner";
private PdUiDispatcher dispatcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initGui();
try {
initPd();
loadPatch();
} catch (IOException e) {
Log.e(TAG, e.toString());
finish();
}
}
private void initGui() {
setContentView(R.layout.main);
}
private void initPd() throws IOException {
// Configure the audio glue
// int sampleRate = AudioParameters.suggestSampleRate();
int sampleRate = 64;
int inpch = AudioParameters.suggestInputChannels();
PdAudio.initAudio(sampleRate, inpch, 2, 8, true);
// Create and install the dispatcher dispatcher = new PdUiDispatcher();
// PdBase.setReceiver(dispatcher);
}
private void loadPatch() throws IOException {
File dir = getFilesDir();
IoUtils.extractZipResource(getResources().openRawResource(R.raw.patch),
dir, true);
File patchFile = new File(dir, "microphone.pd");
PdBase.openPatch(patchFile.getAbsolutePath());
PdAudio.startAudio(this);
}
#Override
protected void onResume() {
super.onResume();
PdAudio.startAudio(this);
}
#Override
protected void onPause() {
super.onPause();
PdAudio.stopAudio();
}
}

You need a permission for recording audio. Try adding
<uses-permission android:name="android.permission.RECORD_AUDIO" />
to your manifest.

Related

Streaming live camera feed in app using android studio

I'm creating an app that I want to stream my foscam live feed in. I'm pretty new to coding and some of this code is over my head. I found some help getting this far but now am hitting a snag. The app runs but only displays a black screen. I believe i have the manifest and XML code all correct. The problem lies in my code. I hope someone can help me out
package com.rednak.camerastream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity
implements MediaPlayer.OnPreparedListener,
SurfaceHolder.Callback {
final static String USERNAME = "guest";
final static String PASSWORD = "Guest";
final static String RTSP_URL = "rtsp://http://rednak71.ddns.net:8090/live1.sdp";
private MediaPlayer _mediaPlayer;
private SurfaceHolder _surfaceHolder;
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up a full-screen black window.
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = getWindow();
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setBackgroundDrawableResource(android.R.color.black);
setContentView(R.layout.activity_main);
// Configure the view that renders live video.
SurfaceView surfaceView =
(SurfaceView) findViewById(R.id.surfaceView);
_surfaceHolder = surfaceView.getHolder();
_surfaceHolder.addCallback(this);
_surfaceHolder.setFixedSize(320, 240);
}
// More to come…
/*
SurfaceHolder.Callback
*/
#
Override
public void surfaceChanged(
SurfaceHolder sh, int f, int w, int h) {}
#
Override
public void surfaceCreated(SurfaceHolder sh) {
_mediaPlayer = new MediaPlayer();
_mediaPlayer.setDisplay(_surfaceHolder);
Context context = getApplicationContext();
Map headers = getRtspHeaders();
Uri source = Uri.parse(RTSP_URL);
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
}
#
Override
public void surfaceDestroyed(SurfaceHolder sh) {
_mediaPlayer.release();
}
private Map getRtspHeaders() {
Map headers = new HashMap();
String basicAuthValue = getBasicAuthValue(USERNAME, PASSWORD);
headers.put("Authorization", basicAuthValue);
return headers;
}
private String getBasicAuthValue(String usr, String pwd) {
String credentials = usr + ":" + pwd;
int flags = Base64.URL_SAFE | Base64.NO_WRAP;
byte[] bytes = credentials.getBytes();
return "Basic" + Base64.encodeToString(bytes, flags);
}
/*
MediaPlayer.OnPreparedListener
*/
#
Override
public void onPrepared(MediaPlayer mp) {
_mediaPlayer.start();
}
}
Make sure that Android's MediaPlayer can actually open and decode your stream. Right now, if the MediaPlayer cannot handle your stream, you are catching any exception and silently ignoring it:
try {
// Specify the IP camera’s URL and auth headers.
_mediaPlayer.setDataSource(context, source, headers);
// Begin the process of setting up a video stream.
_mediaPlayer.setOnPreparedListener(this);
_mediaPlayer.prepareAsync();
} catch (Exception e) {}
At the very least you should log the error:
} catch (Exception e) {
Log.e("MyApp", "Could not open data source", e);
}
Although the MediaPlayer service will most likely pepper the log with its own errors. So what you should do is review the logcat for any messages from the "VideoDecoder" or similar.
To see the logcat in Android Studio, open the "Android Monitor" tab which is on the bottom by default. If you want to see the unfiltered logcat make sure that in the top-right corner of the Android Monitor view it says "No Filters" instead of "Show only selected application".
I have some new code that links to the Foscam videostream but only grabs the frame when it starts then does not stream. Im closer but still need help. Am i on the right track here?
package com.rednak.camstream;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.VideoView;
public class MainCamActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cam);
VideoView vidView = (VideoView)findViewById(R.id.CamVideoView);
String vidAddress = "http://rednak71.ddns.net:8090/CGIProxy.fcgi? cmd=snapPicture2&usr=guest&pwd=guest&t=";
Uri vidUri = Uri.parse(vidAddress);
vidView.setVideoURI(vidUri);
vidView.start();
}
}

Android activity stops working when reading files from /data/data

My android application is kind of a text editor. I want to display the list of saved files. But whenever the activity listing the files is called, the activity stops. This code works completely fine when run in emulator but not on the actual device. Debugging the application on phone shows that the app stops when it tries to access the path although no error is displayed in logcat.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class File_List extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
Drawable background=getResources().getDrawable(R.drawable.background);
background.setAlpha(100);
final ListView list=(ListView)findViewById(R.id.listView1);
File folder = new File("/data/data/com.example.demo/files"); //for accessing the folder conatining the files
File[] listOfFiles = folder.listFiles(); //for listing the files within the folder
ArrayList<String> liste = new ArrayList<String>();
for(int i=0;i<listOfFiles.length;i++)
{
if(listOfFiles[i].isDirectory()==false)
liste.add(listOfFiles[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, liste);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
// TODO Auto-generated method stub
//Log.e("selected",list.getAdapter().getItem(position).toString());
Common.CommonVar=2;
File file=new File("/data/data/com.example.demo/files/"+list.getAdapter().getItem(position).toString());
String content;
Log.e("file access", file.getName());
try
{
content = new Scanner(file).useDelimiter("\\A").nextLine();
Intent intent=new Intent(File_List.this,MainActivity.class);
intent.putExtra("File_data",content);
startActivity(intent);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Change the line as follows
File folder = new File("/data/data/com.example.demo/files");
if(!folder.exists()){
folder.mkdir();
}

Which Mistake in Webview based Android Browser Application?

I'm making an Android Browser Application. Its splash image opens after loading but afterward it crashes. I haven't found what mistake I have in MainActivity.java code.
When i run the code, my default AVD tells me that my application has crashed.
MainActivity.java
package com.example.package;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity
extends Activity
{
private WebView a;
#SuppressLint({"InlinedApi"})
private BroadcastReceiver b = new a(this);
public void a()
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Google");
localBuilder.setMessage("Are you sure you want to Exit?");
localBuilder.setIcon(2130837505);
localBuilder.setPositiveButton("YES", new d());
localBuilder.setNegativeButton("NO", new e());
localBuilder.show();
}
public void onBackPressed()
{
a();
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(2);
setContentView(2130903042);
this.a = ((WebView)findViewById(2131230720));
this.a.getSettings().setJavaScriptEnabled(true);
this.a.setFocusableInTouchMode(true);
this.a.getSettings().setLoadWithOverviewMode(true);
this.a.getSettings().setUseWideViewPort(true);
this.a.getSettings().setLoadsImagesAutomatically(true);
this.a.loadUrl("http://www.google.com");
this.a.setWebChromeClient(new b(this));
this.a.setDownloadListener(new c());
this.a.setWebViewClient(new f());
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
super.onCreateOptionsMenu(paramMenu);
paramMenu.add(0, 1, 0, "Home").setIcon(2130837506);
paramMenu.add(0, 2, 0, "Downloads").setIcon(2130837504);
paramMenu.add(0, 3, 0, "Back").setIcon(2130837506);
paramMenu.add(0, 4, 0, "Forward").setIcon(2130837505);
paramMenu.add(0, 5, 0, "Refresh").setIcon(2130837509);
return true;
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
{
if ((paramInt == 4) && (this.a.canGoBack()))
{
this.a.goBack();
return true;
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
super.onOptionsItemSelected(paramMenuItem);
switch (paramMenuItem.getItemId())
{
default:
return false;
case 1:
this.a.loadUrl("http://www.google.com");
return true;
case 3:
this.a.goBack();
return true;
case 5:
this.a.reload();
return true;
case 4:
this.a.goForward();
return true;
}
}
protected void onPause()
{
super.onPause();
unregisterReceiver(this.b);
}
#SuppressLint({"InlinedApi"})
protected void onResume()
{
IntentFilter localIntentFilter = new IntentFilter("android.intent.action.DOWNLOAD_COMPLETE");
registerReceiver(this.b, localIntentFilter);
super.onResume();
}
}
a.java
package com.example.package;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.widget.Toast;
class a
extends BroadcastReceiver
{
a(MainActivity paramMainActivity) {}
public void onReceive(Context paramContext, Intent paramIntent)
{
Toast.makeText(paramContext, paramContext.getResources().getString(2131034114), 0).show();
}
public static void finish() {
// TODO Auto-generated method stub
}
public static void startActivity(Intent localIntent) {
// TODO Auto-generated method stub
}
}
g.java
package com.example.package;
import android.app.Activity;
import android.content.Intent;
import java.util.TimerTask;
class g
extends TimerTask
{
private Object a;
g(splash paramsplash) {}
public void run()
{
((Activity) this.a).finish();
Intent localIntent = new Intent();
((Activity) this.a).startActivity(localIntent);
}
}
Your problem is almost certainly the issue:
this.a = ((WebView)findViewById(2131230720));
The number "2131230720" is a static reference int to resources, in this case a layout view in your Activity. That number comes from R.java which is created when you "build" your project. Each time you perform a build, it will assign an integer to layout objects, strings, etc. that you define in XML in your res folder.
Using the integer value might work for a while (or is present in source code), but then you change your layouts (or other R objects like strings) or rebuild on a different machine, Android library, etc. and it doesn't work anymore;
That line should look like this:
this.a = ((WebView)findViewById(R.id.my_webview_layout_id));
where "my_webview_layout_id" is from your layout XML file. You should find the "id" of the XML defined object in an XML file in res/layout Use that #+id reference. That will keep track of changes to that static reference.
Then when you build or rebuild your Android app, it will create the R.java file with all of the appropriate references.

Use phone number outside the app?

I don't know if it's possible but in my app I got an activity that show a phone number (retrieve from the web).
Can I send this number to the main phone app of android? For example to call it or save it?
You can create a tel:... Uri, where the ... is replaced by your phone number, then use that Uri with ACTION_DIAL or ACTION_CALL. For example:
package com.commonsware.android.dialer;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class DialerDemo extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
public void dial(View v) {
EditText number=(EditText)findViewById(R.id.number);
String toDial="tel:"+number.getText().toString();
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(toDial)));
}
}
The code shown above is from this sample project.

Android: Internet works in emulator but not on my phone

I'm making an app which reads a certain part of a website and posts it to the screen. The app currently works in my android emulator but when I transfer it to my galaxy S2, it doesn't seem to access the website at all.
package com.example.beam;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
String current = null;
Button check;
TextView text;
TextView url;
String[] lines = new String[12];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
check = (Button) findViewById(R.id.checkstatus);
text = (TextView) findViewById(R.id.textView1);
url = (TextView) findViewById(R.id.url);
String[] lines = new String[12];
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// Attempt to the read the source from a website.
String bodyHtml = "null";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.spring8.or.jp/ext/ja/status/text.html");
ResponseHandler<String> resHandler = new BasicResponseHandler();
try {
bodyHtml = httpClient.execute(httpGet, resHandler);
} catch (Exception e) {
e.printStackTrace();
}
double current = 0;
try{
String derp = bodyHtml.substring(bodyHtml.lastIndexOf("mA") - 5, bodyHtml.lastIndexOf("mA"));
current = Double.parseDouble(derp);
}
catch(Exception e){
}
url.setText(current + " mA");
}
});
}
}
Apologies if the coding is a bit poor and messy, I'm quite new to all this. How do I fix this issue? Thank you
Also, I'm pretty sure I've set the permission correctly in the manifest.
Try this....
Its a good practice to Keep the UI work on UI thread and Non-UI work on Non-UI thread, but that became a LAW from the release of HONEYCOMB Android version.... That may be causing the error.
So you can do the following....
Do the Http on a separate thread, and then place the value on the UI using Handler, Handler Keep the reference of the thread in which it was created.
You can use AsyncTask which is specially designed for android to make a sync between
UI and Non-UI thread.
Note:
Please check the Internet Permission in AndroidManifest, though i know you have done it, cause the app ran on the emulator.... but still..no harm in checking it again.

Categories