Vous êtes sur la page 1sur 14

package in.ac.iitb.www.

imscope;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.AsyncTask;
//import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.view.View.OnFocusChangeListener;
import android.content.Context;

import com.cuboid.cuboidcirclebutton.CuboidButton;
import com.jjoe64.graphview.DefaultLabelFormatter;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GridLabelRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
//import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.NumberFormat;

import in.ac.iitb.www.imscope.CircularSeekBar.OnCircularSeekBarChangeListener;

public class ImScope extends AppCompatActivity {


private CircularSeekBar Freq_seekBar, Time_seekBar, Amp_seekBar;
private EditText Amp_text, Start_text, End_text, Dura_text;
private GraphView graph;
private AudioManager audioManager;

public Boolean recording;

int freq_progress,time_progress,amp_progress, Lfreq_progress, Hfreq_progress;


int max, min, dec, serie, k, x, lenth;

LineGraphSeries <DataPoint> series;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_im_scope);

setVolumeControlStream(AudioManager.STREAM_MUSIC);
Freq_seekBar = (CircularSeekBar) findViewById(R.id.Frequency_circularSeek);
Time_seekBar = (CircularSeekBar) findViewById(R.id.Duration_circularSeek);
Amp_seekBar = (CircularSeekBar) findViewById(R.id.Amplitude_circularSeek);

Amp_text = (EditText) findViewById(R.id.amp_editText);


Start_text = (EditText) findViewById(R.id.start_editText);
End_text = (EditText) findViewById(R.id.end_editText);
Dura_text = (EditText) findViewById(R.id.sec_editText);

graph = (GraphView) findViewById(R.id.graph);

CuboidButton strt_button = (CuboidButton) findViewById(R.id.start_button);


CuboidButton cyc_button = (CuboidButton) findViewById(R.id.cycle_button);

Dura_text.setOnFocusChangeListener( new OnFocusChangeListener(){


@Override
public void onFocusChange(View v, boolean hasFocus) {

if (!hasFocus){
try {
time_progress =
Integer.parseInt(Dura_text.getText().toString());
if (time_progress > 100 | time_progress < 0 ){

Toast.makeText(getApplicationContext(),"Maximum limit
is 100 Sec",
Toast.LENGTH_SHORT).show();
Dura_text.setText("");
}
else{
Time_seekBar.setProgress(time_progress);
time_progress = time_progress*44100;
//Toast.makeText(getApplicationContext(),time_progress
+ " Sec",
// Toast.LENGTH_SHORT).show();
}
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}

}
});

Amp_text.setOnFocusChangeListener( new OnFocusChangeListener(){


@Override
public void onFocusChange(View v, boolean hasFocus) {

if (!hasFocus){
try {
amp_progress =
Integer.parseInt(Amp_text.getText().toString());
if (amp_progress > 1000 | amp_progress < 0 ) {
Toast.makeText(getApplicationContext(), "Maximum limit
is 1000 mV",
Toast.LENGTH_SHORT).show();
Amp_text.setText("");

//Toast.makeText(getApplicationContext(),time_progress*10 + " Sec",


// Toast.LENGTH_SHORT).show();
}
else{
Amp_seekBar.setProgress(amp_progress);

audioManager = (AudioManager)
getSystemService(Context.AUDIO_SERVICE);
int max_vol =
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float point = (Amp_seekBar.getMax())/max_vol;
int value = Math.round(amp_progress/point);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
value, 0);
}
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
});

Start_text.setOnFocusChangeListener( new OnFocusChangeListener(){


@Override
public void onFocusChange(View v, boolean hasFocus) {

if (!hasFocus){
try {
Lfreq_progress =
Integer.parseInt(Start_text.getText().toString());
if (Lfreq_progress > 20000 | Lfreq_progress < 0 ) {
Toast.makeText(getApplicationContext(), "Maximum limit
is 20000 Hz",
Toast.LENGTH_SHORT).show();
Start_text.setText("");

//Toast.makeText(getApplicationContext(),time_progress*10 + " Sec",


// Toast.LENGTH_SHORT).show();
}
else{
Freq_seekBar.setProgress(Lfreq_progress);
//Toast.makeText(getApplicationContext(),Lfreq_progress
+ " Hz",
// Toast.LENGTH_SHORT).show();
}
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}

}
});

End_text.setOnFocusChangeListener( new OnFocusChangeListener(){


@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
try {
Hfreq_progress =
Integer.parseInt(End_text.getText().toString());
if (Hfreq_progress > 20000 | Hfreq_progress < 0 ) {
Toast.makeText(getApplicationContext(), "Maximum limit
is 20000 Hz",
Toast.LENGTH_SHORT).show();
End_text.setText("");
}
else{
Freq_seekBar.setProgress(Hfreq_progress);
//Toast.makeText(getApplicationContext(),Hfreq_progress
+ " Hz",
// Toast.LENGTH_SHORT).show();
}
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}

}
});

Freq_seekBar.setOnSeekBarChangeListener( new
OnCircularSeekBarChangeListener() {

@Override
public void onProgressChanged(CircularSeekBar circularSeekBar, int
progress, boolean fromUser) {
freq_progress = progress;
}

@Override
public void onStopTrackingTouch(CircularSeekBar seekBar) {
if (freq_progress == 0){
Start_text.setText("");
End_text.setText("");
}
else {
Toast.makeText(getApplicationContext(),freq_progress+" Hz",
Toast.LENGTH_SHORT).show();
Start_text.setText(String.format("%d",freq_progress));
End_text.setText(String.format("%d",freq_progress));

Lfreq_progress =
Integer.parseInt(End_text.getText().toString());
Hfreq_progress =
Integer.parseInt(End_text.getText().toString());

}
}

@Override
public void onStartTrackingTouch(CircularSeekBar seekBar) {
Start_text.setText("");
End_text.setText("");
}
});

Time_seekBar.setOnSeekBarChangeListener( new
OnCircularSeekBarChangeListener() {

@Override
public void onProgressChanged(CircularSeekBar circularSeekBar, int
progress, boolean fromUser) {
time_progress = progress;
}

@Override
public void onStopTrackingTouch(CircularSeekBar seekBar) {
if (time_progress == 0){
Dura_text.setText("");
}
else {
Toast.makeText(getApplicationContext(),time_progress+" Sec",
Toast.LENGTH_SHORT).show();
Dura_text.setText(String.format("%d",time_progress));

time_progress = time_progress*44100;
}
}

@Override
public void onStartTrackingTouch(CircularSeekBar seekBar) {
Dura_text.setText("");
}
});

Amp_seekBar.setOnSeekBarChangeListener( new
OnCircularSeekBarChangeListener() {

@Override
public void onProgressChanged(CircularSeekBar circularSeekBar, int
progress, boolean fromUser) {
amp_progress = progress;
}

@Override
public void onStopTrackingTouch(CircularSeekBar seekBar) {
if (amp_progress == 0){
Amp_text.setText("");
//amp_progress = 1;

}
else if (0 < amp_progress & amp_progress< 1000) {
Toast.makeText(getApplicationContext(), amp_progress + " mV",
Toast.LENGTH_SHORT).show();

Amp_text.setText(String.format("%d",amp_progress));

audioManager = (AudioManager)
getSystemService(Context.AUDIO_SERVICE);
int max_vol =
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float point = (Amp_seekBar.getMax())/max_vol;
int value = Math.round(amp_progress/point);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value,
0);
}

else if(amp_progress ==1000) {


int toast_progress;
toast_progress = amp_progress/1000;

Toast.makeText(getApplicationContext(), toast_progress + " V",


Toast.LENGTH_SHORT).show();
Amp_text.setText(String.format("%d",amp_progress));
audioManager = (AudioManager)
getSystemService(Context.AUDIO_SERVICE);
int max_vol =
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
max_vol, 0);
}
}

@Override
public void onStartTrackingTouch(CircularSeekBar seekBar) {
Amp_text.setText("");
}
});

strt_button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), freq_progress + " Hz"+ "
" + Lfreq_progress + " Hz"+ " " + Hfreq_progress + " Hz",
// Toast.LENGTH_SHORT).show();

if (Lfreq_progress == Hfreq_progress & Hfreq_progress != 0 &


time_progress != 0){

new
record_Sound().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new
play_Sound_Single_Tone().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}
else if (Lfreq_progress < Hfreq_progress & time_progress != 0){

new
record_Sound().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new
play_Sound_Multi_Tone().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

else {
if (Lfreq_progress == Hfreq_progress & Hfreq_progress == 0){
Toast.makeText(getApplicationContext(), "Set the
Frequency",
Toast.LENGTH_SHORT).show();
}
else if (time_progress == 0){
Toast.makeText(getApplicationContext(), "Set the Duration",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Start frequency
can't be greater than End frequency",
Toast.LENGTH_SHORT).show();
Start_text.setText("");
End_text.setText("");
}

});

cyc_button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

}
});

private void playSound (double frequency, int duration) {

try {
File in_file = new File(Environment.getExternalStorageDirectory(),
freq_progress + " Hz.pcm");
in_file.createNewFile();

OutputStream in_outputStream = new FileOutputStream(in_file);


BufferedOutputStream in_bufferedOutputStream = new
BufferedOutputStream(in_outputStream);
DataOutputStream in_dataOutputStream = new
DataOutputStream(in_bufferedOutputStream);

// AudioTrack definition
int mBufferSize = AudioTrack.getMinBufferSize(44100,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_8BIT);

AudioTrack mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,


44100,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
mBufferSize, AudioTrack.MODE_STREAM);

// Sine wave
double[] mSound = new double[duration];
short[] mBuffer = new short[duration];
for (int i = 0; i < mSound.length; i++) {
mSound[i] = Math.sin((2.0*Math.PI * i/(44100/frequency)));
mBuffer[i] = (short) (mSound[i]*Short.MAX_VALUE);
in_dataOutputStream.writeShort(mBuffer[i]);
}

in_dataOutputStream.close();

//noinspection deprecation
mAudioTrack.setStereoVolume(AudioTrack.getMaxVolume(),
AudioTrack.getMaxVolume());
mAudioTrack.play();

mAudioTrack.write(mBuffer, 0, mSound.length);
mAudioTrack.stop();
mAudioTrack.release();

} catch (IOException e) {
e.printStackTrace();
}

private void startRecord(){

File file = new File(Environment.getExternalStorageDirectory(),


"imscope_out_data.pcm");

try {
file.createNewFile();

OutputStream outputStream = new FileOutputStream(file);


BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new
DataOutputStream(bufferedOutputStream);

int minBufferSize = AudioRecord.getMinBufferSize(44100,


AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);

short[] audioData = new short[minBufferSize];

AudioRecord audioRecord = new


AudioRecord(MediaRecorder.AudioSource.MIC,
44100,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);

audioRecord.startRecording();

while(recording){
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++){
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
dataOutputStream.close();

} catch (IOException e) {
e.printStackTrace();
}

private class play_Sound_Single_Tone extends AsyncTask<String, Integer,


Integer> {

@Override
protected Integer doInBackground(String... params) {
playSound(freq_progress, time_progress);
return null;
}

@Override
protected void onPostExecute(Integer result) {
//Toast.makeText(getApplicationContext(),"Thread
over",Toast.LENGTH_SHORT).show();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
recording = false;

File file = new File(Environment.getExternalStorageDirectory(),


freq_progress + " Hz.pcm");
int shortSizeInBytes = Short.SIZE/Byte.SIZE;

int i = 0, o = 0;
int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes);
short[] audioData = new short[bufferSizeInBytes];
double[] data = new double[audioData.length/2];
double[] fft_data_x = new double[1024];
double[] fft_data_y = new double[1024];

InputStream inputStream;
try {
inputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new
BufferedInputStream(inputStream);
DataInputStream dataInputStream = new
DataInputStream(bufferedInputStream);

while(dataInputStream.available() > 0){


audioData[i] = dataInputStream.readShort();
i++;
}

dataInputStream.close();

for (int q = 0; q < audioData.length; q = q + 2){


data[o] = 256*audioData[q]+audioData[q+1];
if (data[o]>32767){
data[o] = data[o]-32767;
}

o++;

int data_length = data.length;


int e = 0, fre;

for (int w = data_length/2; w < (data_length/2)+1024; w++){


fft_data_x[e] = data[w];
fft_data_y[e] = 0;
e++;
}

FFT input = new FFT(1024);


input.fft(fft_data_x,fft_data_y);

double [] abs = new double[1024];

series = new LineGraphSeries<>();

graph.removeAllSeries();

GridLabelRenderer gridLabel = graph.getGridLabelRenderer();


gridLabel.setHorizontalAxisTitle("Frequency (Hz)");
gridLabel.setVerticalAxisTitle("Power");

NumberFormat nf = NumberFormat.getNumberInstance();

for (int r = 0; r < 1024; r++){


abs[r] = Math.sqrt(Math.pow(fft_data_x[r],2) +
Math.pow(fft_data_y[r],2));
fre = r*(44100/2048);
series.appendData(new DataPoint(fre,abs[r]),true,1024);
}

graph.addSeries(series);

//nf.setMinimumFractionDigits(3);
nf.setMinimumIntegerDigits(3);
nf.setMaximumIntegerDigits(4);
//nf.setMaximumFractionDigits(0);

gridLabel.setLabelFormatter(new DefaultLabelFormatter(nf, nf));

graph.getViewport().setMaxX(2000);
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setYAxisBoundsManual(true);

} catch (IOException e) {
e.printStackTrace();
}

}
}
private class play_Sound_Multi_Tone extends AsyncTask<String, Integer, Integer>
{

@Override
protected void onPreExecute(){

@Override
protected Integer doInBackground(String... params) {

max = (int) Math.pow(10,Math.floor(Math.log10(Hfreq_progress)));


min = (int) Math.pow(10,Math.floor(Math.log10(Lfreq_progress)));

int max_dec = (int) Math.log10(max);


int min_dec = (int) Math.log10(min);

dec = max_dec - min_dec;

x = min_dec;
k = (int) Math.pow(10,x);

serie = ((dec*10)-(dec-1));

int[] number = new int[serie];

do {
for (int i = 0; i <= 8; i++){
serie--;
number[serie] = (i+1)*k;
}
x++;
k = (int) Math.pow(10,x);

}while (serie > 1);

number[0] = max;
lenth = number.length;

if (Hfreq_progress == 20000){
playSound(Hfreq_progress, time_progress);
}

for (int j = 0; j < lenth; j++){

freq_progress = number[j];
playSound(number[j],time_progress);

}
return null;
}

@Override
protected void onPostExecute(Integer result) {
Toast.makeText(getApplicationContext(),"Thread
over",Toast.LENGTH_SHORT).show();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
recording = false;
}
}

private class record_Sound extends AsyncTask<String, Integer, Integer> {

@Override
protected void onPreExecute(){
recording = true;
}

@Override
protected Integer doInBackground(String... params) {
//recording = true;
startRecord();
return null;
}

@Override
protected void onPostExecute(Integer result) {
//Toast.makeText(getApplicationContext(), "Recording Thread over",
Toast.LENGTH_SHORT).show();

}
}

private void getMaximum_Value(int[] array){

for (int i = 0; i < length.array){

private class FFT {

int n, m;

// Lookup tables. Only need to recompute when size of FFT changes.


double[] cos;
double[] sin;

FFT(int n) {
this.n = n;
this.m = (int) (Math.log(n) / Math.log(2));

// Make sure n is a power of 2


if (n != (1 << m))
throw new RuntimeException("FFT length must be power of 2");

// precompute tables
cos = new double[n / 2];
sin = new double[n / 2];

for (int i = 0; i < n / 2; i++) {


cos[i] = Math.cos(-2 * Math.PI * i / n);
sin[i] = Math.sin(-2 * Math.PI * i / n);
}

void fft(double[] x, double[] y) {


int i, j, k, n1, n2, a;
double c, s, t1, t2;

// Bit-reverse
j = 0;
n2 = n / 2;
for (i = 1; i < n - 1; i++) {
n1 = n2;
while (j >= n1) {
j = j - n1;
n1 = n1 / 2;
}
j = j + n1;

if (i < j) {
t1 = x[i];
x[i] = x[j];
x[j] = t1;
t1 = y[i];
y[i] = y[j];
y[j] = t1;
}
}

// FFT
//n1 = 0;
n2 = 1;

for (i = 0; i < m; i++) {


n1 = n2;
n2 = n2 + n2;
a = 0;

for (j = 0; j < n1; j++) {


c = cos[a];
s = sin[a];
a += 1 << (m - i - 1);

for (k = j; k < n; k = k + n2) {


t1 = c * x[k + n1] - s * y[k + n1];
t2 = s * x[k + n1] + c * y[k + n1];
x[k + n1] = x[k] - t1;
y[k + n1] = y[k] - t2;
x[k] = x[k] + t1;
y[k] = y[k] + t2;
}
}
}
}
}

Vous aimerez peut-être aussi