Catch the note

In questo articolo rendo pubblico, a titolo di esempio, il codice java principale della mia app CatchTheNote, disponibile in versione completa alla voce di menù Android.

package com.andreabianchini.catchthenote;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private SoundPool soundPool;
    private int soundID,tone;
    private int a,as,b,c,cs,d,ds,e,f,fs,g,gs;
    boolean plays = false, loaded = false;
    float actVolume, maxVolume, volume;
    AudioManager audioManager;
    int counter;
    int [] notes=new int[8];
    int [] notesId=new int[8];
    int nnotes=1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // AudioManager audio settings for adjusting the volume
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        actVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volume = actVolume / maxVolume;

        //Hardware buttons setting to adjust the media sound
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

        // the counter will help us recognize the stream id of the sound played  now
        counter = 0;

        // Load the sounds
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                loaded = true;
                plays=false;
            }
        });

        a = soundPool.load(this, R.raw.a, 1);
        as = soundPool.load(this, R.raw.as, 1);
        b = soundPool.load(this, R.raw.b, 1);
        c = soundPool.load(this, R.raw.c, 1);
        cs = soundPool.load(this, R.raw.cs, 1);
        d = soundPool.load(this, R.raw.d, 1);
        ds = soundPool.load(this, R.raw.ds, 1);
        e = soundPool.load(this, R.raw.e, 1);
        f = soundPool.load(this, R.raw.f, 1);
        fs = soundPool.load(this, R.raw.fs, 1);
        g = soundPool.load(this, R.raw.g, 1);
        gs = soundPool.load(this, R.raw.gs, 1);

        soundID = a;
        nnotes=1;
        notes[0]=0;
        notesId[0]=a;

        Button button =  findViewById(R.id.btPlay);
        Button button1 =  findViewById(R.id.btA);
        Button btChange =  findViewById(R.id.btChange);
        Button btShow =  findViewById(R.id.btShow);
        Button btInfo =  findViewById(R.id.btInfo);
        EditText etNNotes = findViewById(R.id.etNNotes);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSound(v);
           }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playA(v);
            }
        });

        btChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeNote(v);
            }
        });

        btShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNote(v);
            }
        });

        btInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showInfo(v);
            }
        });

        etNNotes.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "8")});

        // Initialize the Mobile Ads SDK
        MobileAds.initialize(this, getString(R.string.admob_app_id));

        AdView mBannerAd;

        mBannerAd = findViewById(R.id.adView);

        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mBannerAd.loadAd(adRequest);

    }

    public void showInfo(View v) {
        Intent intent = new Intent(MainActivity.this, Info.class);
        startActivity(intent);

    }

    public void showNote(View v) {
        TextView tv  =  findViewById(R.id.tvNote);
        EditText etNNotes = findViewById(R.id.etNNotes);
        nnotes = Integer.parseInt(etNNotes.getText().toString());
        String s;
        s="";
        for(int i=0;i<nnotes;i++) {
            switch (notes[i]) {
                case 0:
                    s+="A ";
                    break;
                case 1:
                    s+="A# ";
                    break;
                case 2:
                    s+="B ";
                    break;
                case 3:
                    s+="C ";
                    break;
                case 4:
                    s+="C# ";
                    break;
                case 5:
                    s+="D ";
                    break;
                case 6:
                    s+="D# ";
                    break;
                case 7:
                    s+="E ";
                    break;
                case 8:
                    s+="F ";
                    break;
                case 9:
                    s+="F# ";
                    break;
                case 10:
                    s+="G ";
                    break;
                case 11:
                    s+="G# ";
                    break;

            }
        }
        tv.setText(s);
    }

    public void changeNote(View v) {
        EditText etNNotes = findViewById(R.id.etNNotes);
        nnotes = Integer.parseInt(etNNotes.getText().toString());
        int last,last1;
        last1=2;
        last=1;
        for(int i=0;i<nnotes;i++) {
            tone=0;
            if (i>1)
            while(tone==last || (Math.abs(tone-last)==1 && Math.abs(last1-last)==1) || (Math.abs(tone-last)==3 && Math.abs(last1-last)==3) || (Math.abs(tone-last)==2 && Math.abs(last1-last)==3) || (Math.abs(tone-last)==3 && Math.abs(last1-last)==2)) {
                tone = new Random().nextInt(12);
            }
            else
                tone = new Random().nextInt(12);
            last1 = last;
            last = tone;
            notes[i]=tone;
            switch (tone) {
                case 0:
                    soundID = a;
                    break;
                case 1:
                    soundID = as;
                    break;
                case 2:
                    soundID = b;
                    break;
                case 3:
                    soundID = c;
                    break;
                case 4:
                    soundID = cs;
                    break;
                case 5:
                    soundID = d;
                    break;
                case 6:
                    soundID = ds;
                    break;
                case 7:
                    soundID = e;
                    break;
                case 8:
                    soundID = f;
                    break;
                case 9:
                    soundID = fs;
                    break;
                case 10:
                    soundID = g;
                    break;
                case 11:
                    soundID = gs;
                    break;

            }
            notesId[i]=soundID;
        }
    }

    public void playSound(View v) {
        // Is the sound loaded does it already play?
        TextView tv  =  findViewById(R.id.tvNote);
        tv.setText(getString(R.string.note));

        for (int i=0;i<nnotes;i++){
        if (loaded && !plays) {
            soundPool.play(notesId[i], 1, 1, 0, 0, 1);
            counter = counter++;
            //Toast.makeText(this, "Played sound", Toast.LENGTH_SHORT).show();
            //plays = true;
        }
            try { Thread.sleep(1600); }
            catch (InterruptedException ex) { android.util.Log.d("Catch the Note", ex.toString()); }        }
    }

    public void playA(View v) {
        // Is the sound loaded does it already play?
        TextView tv  =  findViewById(R.id.tvNote);
        tv.setText(getString(R.string.note));

            if (loaded && !plays) {
                soundPool.play(a, 1, 1, 0, 0, 1);
                counter = counter++;
                //Toast.makeText(this, "Played sound", Toast.LENGTH_SHORT).show();
                //plays = true;
            }
            try { Thread.sleep(1600); }
            catch (InterruptedException ex) { android.util.Log.d("Catch the Note", ex.toString()); }
    }

    public void playLoop(View v) {
        // Is the sound loaded does it already play?
        if (loaded && !plays) {

            // the sound will play for ever if we put the loop parameter -1
            soundPool.play(soundID, volume, volume, 1, -1, 1f);
            counter = counter++;
            Toast.makeText(this, "Plays loop", Toast.LENGTH_SHORT).show();
            plays = true;
        }
    }

    public void pauseSound(View v) {
        if (plays) {
            soundPool.pause(soundID);
//            soundID = soundPool.load(this, R.raw.beep, counter);
            Toast.makeText(this, "Pause sound", Toast.LENGTH_SHORT).show();
            plays = false;
        }
    }

    public void stopSound(View v) {
        if (plays) {
            soundPool.stop(soundID);
//            soundID = soundPool.load(this, R.raw.beep, counter);
            Toast.makeText(this, "Stop sound", Toast.LENGTH_SHORT).show();
            plays = false;
        }
    }

    public class InputFilterMinMax implements InputFilter {

        private int min, max;

        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public InputFilterMinMax(String min, String max) {
            this.min = Integer.parseInt(min);
            this.max = Integer.parseInt(max);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) { }
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }
    }