TarsosDSP in Android Studio - android-studio

This is my first post on SO and I am trying to combine my music skills with computer science.
I am using Android studio 3.1.2 with gradle 4.5, Nexus 5X, API 25, Android 7.1.1, Windows 7.
I followed very careful these instructions:
Create a project called Pitchbender
Download the .jar of TarsosDSP and included in
C:\Users\Carlos\AndroidStudioProjects\Pitchbender\app\libs\TarsosDSP-Android-latest
I checked the build.gradle of my project:
dependencies { implementation fileTree(dir: ‘libs’, include: [‘*.jar’]) }
In my project, I have the following imports automatically done by Android Studio:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.io.android.AudioDispatcherFactory
import be.tarsos.dsp.pitch.PitchDetectionHandler
import be.tarsos.dsp.pitch.PitchDetectionResult
import be.tarsos.dsp.pitch.PitchProcessor
import kotlinx.android.synthetic.main.activity_main.*
import be.tarsos.dsp.pitch.PitchProcessor.PitchEstimationAlgorithm
import be.tarsos.dsp.AudioProcessor
import android.widget.TextView
import be.tarsos.dsp.AudioDispatcher
I have this permission in my manifest file
uses-permission android:name=”android.permission.RECORD_AUDIO”
Android Studio gives the option to convert to Kotlin the first line of the following code:
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
If I respond to “No” to the Kotlin conversion, I have the following compilation error:
Clasifier “AudioDispatcher” does not have any companion object, and thus must be initialized here.
What can I do?
If I respond “Yes” to the Kotlin conversion question, that statement is converted to
val dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0)
and then, when I run this program, Android informs me that there is an error and closes my project and keeps closing my project. What to do?
Please help to run at least that first instruction of the complete code:
PitchDetectionHandler pdh = new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult res, AudioEvent e){
final float pitchInHz = res.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
processPitch(pitchInHz);
}
});
}
};
AudioProcessor pitchProcessor = new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(pitchProcessor);
Thread audioThread = new Thread(dispatcher, "Audio Thread");
audioThread.start();
Question:
Do you have any simple project in Android Studio, so that I can see what my errors are?

I had a similar problem when I tried to run this example and my solution (Sep. 2019) was to add a runtime confirmation of the record permission. I'm not sure if it's the same case, buuuut
Here is my code to it:
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}

Related

Android Studio 3.2.1: Silent Mode Toggle app crashes when clicked even though no error in code

I'm just starting to learn coding for Android App by following the book Android App Development for Dummies to create the Silent Mode Toggle App.
Everything seems fine in the code (no error except for warning that:
"Casting 'findViewById(R.id.phone_icon)' to 'ImageView' is redundant.
This inspection reports unnecessary cast expressions."
I have read through a similar problem here (Application Crashes - Silent Mode Toggle - Android for Dummies) and it says to try:
1) Change "extends ActionBarActivity" to just "extends Activity" and import - mine is already as such.
2) delete or comment the 'if' in the onCreate method out - mine don't have this section.
3) change the parameter of the setContentView to: R.layout.fragment_main - not very sure what this means but don't seem to be relevant to my code? (his codes and mine are slightly different)
MainActivity.java Code
package com.dummies.silentmodetoggle;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.dummies.silentmodetoggle.util.RingerHelper;
public class MainActivity extends Activity {
AudioManager audioManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
setContentView(R.layout.activity_main);
FrameLayout contentView =
(FrameLayout) findViewById(R.id.content);
contentView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RingerHelper.performToggle(audioManager);
updateUi();
}
});
}
private void updateUi() {
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
int phoneImage = RingerHelper.isPhoneSilent(audioManager)
? R.mipmap.ringer_off
: R.mipmap.ringer_on;
imageView.setImageResource(phoneImage);
}
#Override
protected void onResume(){
super.onResume();
// Update our UI in case anything has changed.
updateUi();
}
}
RingerHelper.java
The book says to create a java file at: "src/main/java/com/dummies/silentmodetoggle/util/RingerHelper.java" but did not state how. Since I do not have a util folder so I'd created a package (New>Package) at "src/main/java/com.dummies.silentmodetoggle" and added the RingerHelper java file in the util folder. Note sure if this is the problem? The code is as below:
package com.dummies.silentmodetoggle.util;
import android.media.AudioManager;
public class RingerHelper {
// private to prevent users from creating a RingerHelper object
private RingerHelper(){}
/* Toggles the phone's silent mode */
public static void performToggle(AudioManager audioManager) {
// If the phone is currently silent, then unsilence it. If
// it's currently normal, then silence it.
audioManager.setRingerMode(
isPhoneSilent(audioManager)
? AudioManager.RINGER_MODE_NORMAL
: AudioManager.RINGER_MODE_SILENT);
}
/* Returns whether the phone is currently in silent mode. */
public static boolean isPhoneSilent(AudioManager audioManager){
return audioManager.getRingerMode()
== AudioManager.RINGER_MODE_SILENT;
}
}
Error from LogCat when I clicked the button on app
2018-12-01 22:11:44.029 30122-30122/com.dummies.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dummies.silentmodetoggle, PID: 30122
java.lang.SecurityException: Not allowed to change Do Not Disturb state
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
at com.dummies.silentmodetoggle.util.RingerHelper.performToggle(RingerHelper.java:13)
at com.dummies.silentmodetoggle.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2018-12-01 22:11:44.672 1315-1315/? E/EGL_emulation: tid 1315: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
Otherwise the app seems to work fine, ie, when I click on the volume button of the device itself to silent, the app image will change to silent and vice versa. It just crashes when I try to click on the image of the app itself.
I really have no idea what's going on. Please help. Thanks very much!
You need to add permissions for Do Not Disturb State. I was facing the same issue and I added the following lines to my Main_Activity.java code in onCreate method and it works fine Now:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}

Google-play-services and INSTALL_PARSE_FAILED_MANIFEST_MALFORMED

I'm migrating from Eclipse to Android Studio. When I integrate Google-play-services into my project, I fail to install the APK to a device with the following error: "INSTALL_PARSE_FAILED_MANIFEST_MALFORMED". How come eerrApparently Android Studio and this library has a compatibility issue with my legacy app's package name which starts with an uppercase letter. When I change the first letter of the package name (ApplicationId in Android Studio) to lower, everything is fine. Note that my base package name is all lowercase. The problem is with ApplicationId.
The app is live on the store for a few years now and I don't want to upload it as a new app.
Really stuck on this - is there a workaround?
Please refer to Naming Conventions
You can not simply use upper case with package name anymore.
This worked for me:
Instead of importing the eclipse project into Android Studio,
(1) Create a new Android Studio project with the package name that you have already put on the Google Play Store but use all lower case.
(2) Then copy all your files into the Android Studio project.
(3) Change the package ID in the build.gradle (Module App) file with the original package name with upper case (see below) and sync (this will create the package name in the apk with the original package name with upper case chars and it will upload to the Google Play Store and replace your old one!!!
(4) This installed the apk (with uppercase package name) onto my test phone and it worked perfectly.
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "DrWebsterApps.New.England.Patriots.Game"
minSdkVersion 9
targetSdkVersion 21
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
(5) as a test case here is code that pops up the currently running app's package name to proof it:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ListActivity;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* put this in the manifest.xml file!!!
<uses-permission android:name="android.permission.GET_TASKS"/>
*/
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
createDialogAnswer(taskInfo.get(0).topActivity.getPackageName());
}
public void createDialogAnswer(String msg) {
AlertDialog.Builder adb;
LinearLayout linear = new LinearLayout(this);
linear.setBackgroundColor(Color.RED);
linear.setOrientation(LinearLayout.VERTICAL);
adb = new AlertDialog.Builder(this);
// String team = (string)R.string.app_name;
adb.setTitle(" Trivia App");
adb.setView(linear);
LayoutInflater mInflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View PopUpView = mInflater.inflate(R.layout.scores, linear);
TextView mytext = (TextView) PopUpView.findViewById(R.id.QPopUp);
// mytext.setTextColor(getResources().getColor(R.color.White));
// mytext.setTextSize(getResources().getDimension(R.dimen.aboutApp_text_size));
mytext.append(msg + " \n");
adb.setNegativeButton("Quit", myDialogOnClickListener);
adb.show();
}
DialogInterface.OnClickListener myDialogOnClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface v, int x) {
finish();
}
};

Native Interface for J2Me device Codename One

I created an Interface class:
package userclasses;
import com.codename1.system.NativeInterface;
public interface NativeJ2MEInterface extends NativeInterface {
public void pollBackground();
}
This is the native class - after I edited it:
package userclasses;
import userclasses.StateMachine;
public class NativeJ2MEInterfaceImpl {
public void pollBackground() {
try {
Date now = new Date();
long timeToRun = now.getTime() + (1000 * 60 );
System.out.println("RUNNNNNNN forest runnn!");
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
}
catch (Exception e) {
System.out.println("EXC-1:"+e.getMessage());
}
}
public boolean isSupported() {
return true;
}
}
I want to call the javax.microedition.io.PushRegistry registerAlarm method, but my Codename One J2ME build fails saying:
error: cannot find symbol
PushRegistry.registerAlarm(StateMachine.class.getName(), timeToRun);
I added a midp_2.1.jar to the native j2me directory, but it did not work.
How can I get this to work? Or how can I directly access j2me alarm API?
Don't add the jar, it will get packaged into the final build.
Try setting the build argument j2me.ashaNative=true.

LWUIT assistance

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class Ruwwa extends javax.microedition.midlet.MIDlet
implements ActionListener{
Form f;
Button mybutton1;
Button mybutton2;
Command exit;
Command ok;
public void startApp() {
Display.init(this);
f = new Form();
try {
Resources r = Resources.open("/mairuwa.res");
UIManager.getInstance().setThemeProps(r.getTheme("Mairuwa Theme"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
mybutton1=new Button("Report A Problem");
mybutton2=new Button("Request Info");
f.setLayout(new BorderLayout());
f.addComponent(BorderLayout.CENTER, new Label("The Mairuwa Portal"));
ok = new Command("OK");
exit = new Command("Exit");
f.addCommand(ok);
f.addCommand(exit);
f.addCommandListener(this);
f.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
notifyDestroyed();
}
}
I would like to add another label under the "The Mairuwa Portal" and also place two buttons ("Report A Problem","Request Information") beneath this as well. An illustration of what I am describing is
label: The Mairuwa Portal
then another label beneath it: I want to:
Then two buttons beneath this Button:Report Problem Button: Request Information
I have been able to add OK and EXIT button to the project,but this above buttons I talked about should as I described.
These buttons will carry functionality. I hope this can be done in LWUIT.
You need to include all JSR's when compiling a LWUIT application in the IDE. LWUIT doesn't require them all to run but requires 184, 226, MMAPI & file connector to compile. This is causing your verification error.
I would recommend developing with the Sun/Oracle simulators and using the more device like emulators for QA.
The exception you got means your application was built incorrectly, see that Ruwwa is in the jar file that was produced by your build. If not fix your build.

Problem in Finding Resource File in Android

Hi i am using Google Maps in a code
This is the code written in the activity file
package com.hellomaps;
import android.app.Activity;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
public class HelloGoogleMaps extends MapActivity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
}
Now in the line setContentView(R.layout.main) it does not recognse "R" and hence mapview cannot be used in the activity as it doesnot recognse the view
I know android.R and com.google.R should not be imported.
i am stuck here .. kindly help..!!
Thanks in Advance
R file is generated when you compile your project. So if you are using eclipse just press ctrl+b and R file should appear in gen folder in your project.
If you checked out project from SVN or some other version control you could have problem with R file. If you do, create new android project in eclipse then copy/paste source and resources from checked out project to new created one and build. Hope this helps.

Resources