├── README.md
├── ic_launcher-web.png
├── res
├── drawable-hdpi
│ └── ic_launcher.png
├── drawable-ldpi
│ └── ic_launcher.png
├── drawable-mdpi
│ └── ic_launcher.png
├── drawable-xhdpi
│ └── ic_launcher.png
├── menu
│ └── activity_main.xml
├── values-v11
│ └── styles.xml
├── values-v14
│ └── styles.xml
├── values
│ ├── strings.xml
│ └── styles.xml
└── layout
│ └── activity_main.xml
├── docs
└── research
├── src
└── com
│ └── github
│ └── shadow
│ ├── events
│ ├── VoiceActivityListeningEvent.java
│ ├── MessageEvent.java
│ └── VoiceActivityDetectedEvent.java
│ ├── config
│ └── EventBusConfig.java
│ ├── processing
│ ├── AudioProcessor.java
│ └── processors
│ │ ├── AudioSimpleMediaRecorder.java
│ │ ├── Audio.java
│ │ └── AudioSimpleAudioRecord.java
│ ├── services
│ └── VoiceActivityDetectorService.java
│ └── Shadow.java
├── .gitignore
├── tests
└── AndroidManifest.xml
├── proguard-project.txt
├── AndroidManifest.xml
├── shadow.iml
└── LICENSE
/README.md:
--------------------------------------------------------------------------------
1 | # shadow
2 |
--------------------------------------------------------------------------------
/ic_launcher-web.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/452/shadow/master/ic_launcher-web.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/452/shadow/master/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/452/shadow/master/res/drawable-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/452/shadow/master/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/452/shadow/master/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/docs/research:
--------------------------------------------------------------------------------
1 | Voice Activity Detection(VAD) то-есть обнаружение тишины в речевом или аудио сигнале http://habrahabr.ru/post/192954/
2 |
3 |
--------------------------------------------------------------------------------
/src/com/github/shadow/events/VoiceActivityListeningEvent.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.events;
2 |
3 | public class VoiceActivityListeningEvent {
4 | }
--------------------------------------------------------------------------------
/src/com/github/shadow/events/MessageEvent.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.events;
2 |
3 | public class MessageEvent {
4 |
5 | private final String data;
6 |
7 | public MessageEvent(String data) {
8 | this.data = data;
9 | }
10 |
11 | public String getData() {
12 | return data;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/res/menu/activity_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/com/github/shadow/config/EventBusConfig.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.config;
2 |
3 | import de.greenrobot.event.EventBus;
4 |
5 | public class EventBusConfig {
6 |
7 | private static EventBus eventBus = EventBus.getDefault();
8 |
9 | public static EventBus getInstance() {
10 | return eventBus;
11 | }
12 |
13 | }
--------------------------------------------------------------------------------
/src/com/github/shadow/processing/AudioProcessor.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.processing;
2 |
3 | public interface AudioProcessor {
4 |
5 | void start();
6 | void stop();
7 | void doIt();
8 | int getVoiceActivityLevel();
9 | void setVoiceActivityLevel(int delayTime);
10 | void setDelayTime(int voiceActivityLevel);
11 | }
12 |
--------------------------------------------------------------------------------
/src/com/github/shadow/events/VoiceActivityDetectedEvent.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.events;
2 |
3 | public class VoiceActivityDetectedEvent {
4 | private double level;
5 |
6 | public VoiceActivityDetectedEvent(double level) {
7 | this.level = level;
8 | }
9 |
10 | public double getLevel() {
11 | return level;
12 | }
13 | }
--------------------------------------------------------------------------------
/res/values-v11/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/res/values-v14/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
8 |
11 |
12 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 | /*/build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 | *~*
29 | .idea
30 |
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Shadow
4 | Play
5 | Start listening
6 | Stop listening
7 | Voice Activity Level:
8 | Time ms:
9 | Audio Files will be saved into \"shadow\" folder
10 |
--------------------------------------------------------------------------------
/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
14 |
15 |
16 |
19 |
20 |
--------------------------------------------------------------------------------
/tests/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 | -keepclassmembers class ** {
22 | public void onEvent*(**);
23 | }
24 |
--------------------------------------------------------------------------------
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
17 |
18 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/src/com/github/shadow/processing/processors/AudioSimpleMediaRecorder.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.processing.processors;
2 |
3 |
4 | import android.media.MediaRecorder;
5 |
6 | import com.github.shadow.processing.AudioProcessor;
7 |
8 | import java.io.IOException;
9 |
10 | public class AudioSimpleMediaRecorder implements AudioProcessor {
11 |
12 | private MediaRecorder recorder;
13 | private int maxAmplitude;
14 |
15 | public void stop() {
16 | recorder.stop();
17 | recorder.release();
18 | }
19 |
20 | public void start() {
21 | recorder = new MediaRecorder();
22 | recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
23 | recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
24 | recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
25 | recorder.setOutputFile("/dev/null");
26 | try {
27 | recorder.prepare();
28 | } catch (IOException e) {
29 | }
30 | recorder.start();
31 | }
32 |
33 | public int getVoiceActivityLevel() {
34 | if (recorder == null) {
35 | return 0;
36 | } else {
37 | return maxAmplitude = recorder.getMaxAmplitude();
38 | }
39 | }
40 |
41 | @Override
42 | public void setVoiceActivityLevel(int delayTime) {
43 |
44 | }
45 |
46 | @Override
47 | public void setDelayTime(int voiceActivityLevel) {
48 |
49 | }
50 |
51 | public double getdbLevel() {
52 | int ratio = maxAmplitude;
53 | int db = 0;
54 | if (ratio > 1)
55 | db = (int) (20 * Math.log10(ratio));
56 | return Math.log10(ratio);
57 | }
58 |
59 |
60 | public void doIt() {
61 | }
62 |
63 | }
--------------------------------------------------------------------------------
/src/com/github/shadow/processing/processors/Audio.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.processing.processors;
2 |
3 |
4 | import android.media.AudioFormat;
5 | import android.media.AudioRecord;
6 | import android.media.MediaRecorder;
7 |
8 | import de.greenrobot.event.EventBus;
9 |
10 | public class Audio {
11 | private EventBus eventBus = EventBus.getDefault();
12 | int sampleSize = 8000;
13 | double fftOutWindowSize = 0;
14 |
15 | void init() {
16 | int channel_config = AudioFormat.CHANNEL_CONFIGURATION_MONO;
17 | int format = AudioFormat.ENCODING_PCM_16BIT;
18 |
19 | int bufferSize = AudioRecord.getMinBufferSize(sampleSize, channel_config, format);
20 | AudioRecord audioInput = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleSize, channel_config, format, bufferSize);
21 |
22 | int bytesRecorded = 0;
23 |
24 |
25 | byte[] audioBuffer = new byte[bufferSize];
26 | audioInput.startRecording();
27 | audioInput.read(audioBuffer, 0, bufferSize);
28 |
29 | double[] micBufferData = new double[bufferSize];
30 | final int bytesPerSample = 2; // As it is 16bit PCM
31 | final double amplification = 100.0; // choose a number as you like
32 | for (int index = 0, floatIndex = 0; index < bytesRecorded - bytesPerSample + 1; index += bytesPerSample, floatIndex++) {
33 | double sample = 0;
34 | for (int b = 0; b < bytesPerSample; b++) {
35 | int v = audioBuffer[index + b];
36 | if (b < bytesPerSample - 1 || bytesPerSample == 1) {
37 | v &= 0xFF;
38 | }
39 | sample += v << (b * 8);
40 | }
41 | double sample32 = amplification * (sample / 32768.0);
42 | micBufferData[floatIndex] = sample32;
43 | }
44 | }
45 |
46 | private double ComputeFrequency(int arrayIndex) {
47 | return ((1.0 * sampleSize) / (1.0 * fftOutWindowSize)) * arrayIndex;
48 | }
49 |
50 | }
--------------------------------------------------------------------------------
/src/com/github/shadow/services/VoiceActivityDetectorService.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.services;
2 |
3 | import android.app.Service;
4 | import android.content.Intent;
5 | import android.os.Handler;
6 | import android.os.IBinder;
7 |
8 | import com.github.shadow.config.EventBusConfig;
9 | import com.github.shadow.events.VoiceActivityDetectedEvent;
10 | import com.github.shadow.processing.AudioProcessor;
11 | import com.github.shadow.processing.processors.AudioSimpleAudioRecord;
12 |
13 | import java.util.Timer;
14 | import java.util.TimerTask;
15 |
16 | import de.greenrobot.event.EventBus;
17 |
18 | public class VoiceActivityDetectorService extends Service {
19 |
20 | private static final String TAG = VoiceActivityDetectorService.class.getCanonicalName();
21 | private EventBus eventBus = EventBusConfig.getInstance();
22 | private VoiceActivityProcessorThread voiceActivityProcessorThread;
23 | private Timer timer = new Timer();
24 | private AudioProcessor audioProcessor = new AudioSimpleAudioRecord();
25 | private final Handler uiHandler = new Handler();
26 |
27 | @Override
28 | public void onCreate() {
29 | super.onCreate();
30 | timer.schedule(new TimerTask() {
31 | @Override
32 | public void run() {
33 | uiHandler.post(new Runnable() {
34 | @Override
35 | public void run() {
36 | if (audioProcessor != null) {
37 | double data = audioProcessor.getVoiceActivityLevel();
38 | eventBus.post(new VoiceActivityDetectedEvent(data));
39 | }
40 | }
41 | });
42 |
43 | }
44 | }, 0, 100);
45 | }
46 |
47 | @Override
48 | public int onStartCommand(Intent intent, int flags, int startId) {
49 | String action = intent.getAction();
50 | if (action.equals("start")) {
51 | voiceActivityProcessorThread = new VoiceActivityProcessorThread();
52 | audioProcessor.setDelayTime(intent.getIntExtra("delayTime", 1789));
53 | audioProcessor.setVoiceActivityLevel(intent.getIntExtra("voiceActivityLevel", 379));
54 | voiceActivityProcessorThread.start();
55 | }
56 | if (action.equals("stop")) {
57 | voiceActivityProcessorThread.stopThis();
58 | }
59 | return START_REDELIVER_INTENT;
60 | }
61 |
62 | private class VoiceActivityProcessorThread extends Thread {
63 |
64 | private volatile boolean isStopped;
65 |
66 | public VoiceActivityProcessorThread() {
67 | }
68 |
69 | @Override
70 | public void run() {
71 | audioProcessor.start();
72 | while (!isStopped) {
73 | audioProcessor.doIt();
74 | }
75 | }
76 |
77 | public void stopThis() {
78 | isStopped = true;
79 | audioProcessor.stop();
80 | }
81 | }
82 |
83 | @Override
84 | public void onDestroy() {
85 | if (voiceActivityProcessorThread != null) {
86 | voiceActivityProcessorThread.stopThis();
87 | }
88 | super.onDestroy();
89 | }
90 |
91 | @Override
92 | public IBinder onBind(Intent intent) {
93 | return null;
94 | }
95 |
96 | }
--------------------------------------------------------------------------------
/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
9 |
14 |
20 |
21 |
29 |
37 |
38 |
39 |
43 |
44 |
52 |
53 |
60 |
61 |
69 |
70 |
77 |
78 |
84 |
85 |
--------------------------------------------------------------------------------
/src/com/github/shadow/Shadow.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.media.AudioManager;
7 | import android.os.Bundle;
8 | import android.view.Menu;
9 | import android.view.MenuItem;
10 | import android.view.View;
11 | import android.widget.Button;
12 | import android.widget.SeekBar;
13 | import android.widget.TextView;
14 |
15 | import com.github.shadow.config.EventBusConfig;
16 | import com.github.shadow.events.MessageEvent;
17 | import com.github.shadow.events.VoiceActivityDetectedEvent;
18 | import com.github.shadow.events.VoiceActivityListeningEvent;
19 | import com.github.shadow.services.VoiceActivityDetectorService;
20 |
21 | import de.greenrobot.event.EventBus;
22 |
23 | public class Shadow extends Activity implements View.OnClickListener {
24 |
25 | private EventBus eventBus = EventBusConfig.getInstance();
26 | private TextView txtViewStatus;
27 | private Button btnStartListening;
28 | private Button btnStopListening;
29 | private SeekBar seekBarVoiceActivityLevel;
30 | private SeekBar seekBarTime;
31 | private Intent voiceActivityDetectorService;
32 | private TextView txtViewVoiceActivityLevel;
33 | private TextView txtViewTime;
34 |
35 | private int delayTime = 1789;
36 | private int voiceActivityLevel = 379;
37 |
38 | private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
39 |
40 | @Override
41 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
42 | if (seekBar.getId() == R.id.seekBarVoiceActivityLevel) {
43 | txtViewVoiceActivityLevel.setText(getString(R.string.VoiceActivityLevel) + progress);
44 | voiceActivityLevel = progress;
45 | } else {
46 | txtViewTime.setText(getString(R.string.Time) + progress);
47 | delayTime = progress;
48 | }
49 | }
50 |
51 | @Override
52 | public void onStartTrackingTouch(SeekBar seekBar) {
53 |
54 | }
55 |
56 | @Override
57 | public void onStopTrackingTouch(SeekBar seekBar) {
58 |
59 | }
60 | };
61 |
62 | @Override
63 | protected void onCreate(Bundle savedInstanceState) {
64 | super.onCreate(savedInstanceState);
65 | setContentView(R.layout.activity_main);
66 | AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
67 | am.setParameters("noise_suppression=auto");
68 | initUI();
69 | voiceActivityDetectorService = new Intent(this, VoiceActivityDetectorService.class);
70 | }
71 |
72 | private void initUI() {
73 | txtViewStatus = (TextView) findViewById(R.id.txtViewStatus);
74 | txtViewVoiceActivityLevel = (TextView) findViewById(R.id.textViewVoiceActivityLevel);
75 | txtViewTime = (TextView) findViewById(R.id.textViewTime);
76 | btnStartListening = (Button) findViewById(R.id.btnStartListening);
77 | btnStartListening.setOnClickListener(this);
78 | btnStopListening = (Button) findViewById(R.id.btnStopListening);
79 | btnStopListening.setOnClickListener(this);
80 | seekBarVoiceActivityLevel = (SeekBar) findViewById(R.id.seekBarVoiceActivityLevel);
81 | seekBarTime = (SeekBar) findViewById(R.id.seekBarTime);
82 | btnStopListening.setEnabled(false);
83 | seekBarVoiceActivityLevel.setOnSeekBarChangeListener(onSeekBarChangeListener);
84 | seekBarTime.setOnSeekBarChangeListener(onSeekBarChangeListener);
85 | txtViewTime.setText(getString(R.string.Time) + delayTime);
86 | txtViewVoiceActivityLevel.setText(getString(R.string.VoiceActivityLevel) + voiceActivityLevel);
87 | }
88 |
89 | public void onClick(View v) {
90 | if (v == btnStartListening) {
91 | voiceActivityDetectorService.setAction("start");
92 | voiceActivityDetectorService.putExtra("delayTime", delayTime);
93 | voiceActivityDetectorService.putExtra("voiceActivityLevel", voiceActivityLevel);
94 | startService(voiceActivityDetectorService);
95 | txtViewStatus.setText("Status: listening");
96 | btnStartListening.setEnabled(false);
97 | seekBarVoiceActivityLevel.setEnabled(false);
98 | seekBarTime.setEnabled(false);
99 | btnStopListening.setEnabled(true);
100 | } else if (v == btnStopListening) {
101 | txtViewStatus.setText("Status: listening ended");
102 | voiceActivityDetectorService.setAction("stop");
103 | startService(voiceActivityDetectorService);
104 | btnStartListening.setEnabled(true);
105 | seekBarVoiceActivityLevel.setEnabled(true);
106 | seekBarTime.setEnabled(true);
107 | btnStopListening.setEnabled(false);
108 | }
109 | }
110 |
111 | public void onEventMainThread(MessageEvent event) {
112 | setStatusTest(event.getData());
113 | }
114 |
115 | private void setStatusTest(String data) {
116 | txtViewStatus.setText("Status: " + data);
117 | }
118 |
119 | public void onEventMainThread(VoiceActivityDetectedEvent event) {
120 | setStatusTest("Voice Activity Detected " + event.getLevel());
121 | }
122 |
123 | public void onEventMainThread(VoiceActivityListeningEvent event) {
124 | setStatusTest("Voice Activity Listening");
125 | }
126 |
127 | @Override
128 | protected void onStart() {
129 | super.onStart();
130 | eventBus.register(this, 1);
131 | }
132 |
133 | @Override
134 | protected void onStop() {
135 | eventBus.unregister(this);
136 | super.onStop();
137 | }
138 |
139 | @Override
140 | public boolean onCreateOptionsMenu(Menu menu) {
141 | getMenuInflater().inflate(R.menu.activity_main, menu);
142 | return true;
143 | }
144 |
145 | @Override
146 | public boolean onOptionsItemSelected(MenuItem item) {
147 | return true;
148 | }
149 |
150 | }
--------------------------------------------------------------------------------
/shadow.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/src/com/github/shadow/processing/processors/AudioSimpleAudioRecord.java:
--------------------------------------------------------------------------------
1 | package com.github.shadow.processing.processors;
2 |
3 |
4 | import android.media.AudioFormat;
5 | import android.media.AudioRecord;
6 | import android.media.MediaRecorder;
7 | import android.os.Environment;
8 |
9 | import com.github.shadow.processing.AudioProcessor;
10 |
11 | import java.io.File;
12 | import java.io.FileNotFoundException;
13 | import java.io.FileOutputStream;
14 | import java.io.IOException;
15 | import java.nio.ByteBuffer;
16 | import java.text.SimpleDateFormat;
17 | import java.util.Date;
18 | import java.util.LinkedList;
19 | import java.util.List;
20 |
21 | public class AudioSimpleAudioRecord implements AudioProcessor {
22 |
23 | private static final int RECORDER_BPP = 16;
24 | private static int RECORDER_SAMPLE_RATE = 8000;
25 | private static int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
26 | private static int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
27 | private File audioFile;
28 |
29 | private boolean isVoiceActivityDetected = false;
30 | private boolean isRecording = false;
31 | private List list = new LinkedList<>();
32 |
33 | private short[] buffer;
34 | private int level;
35 | private long timeDelayStart;
36 |
37 | // Get the minimum buffer size required for the successful creation of an AudioRecord object.
38 | private int bufferSizeInBytes = AudioRecord.getMinBufferSize(RECORDER_SAMPLE_RATE,
39 | RECORDER_CHANNELS,
40 | RECORDER_AUDIO_ENCODING
41 | );
42 | // Initialize Audio Recorder.
43 | private AudioRecord audioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION,
44 | RECORDER_SAMPLE_RATE,
45 | RECORDER_CHANNELS,
46 | RECORDER_AUDIO_ENCODING,
47 | bufferSizeInBytes
48 | );
49 |
50 | private int bufferSizeInShorts = (bufferSizeInBytes / 2);
51 | private int voiceActivityLevel = 379;
52 | private int delayTime = 1789;
53 |
54 | public AudioSimpleAudioRecord() {
55 | init();
56 | }
57 |
58 | private void init() {
59 | // Save audio to file.
60 | String filepath = Environment.getExternalStorageDirectory().getPath();
61 | audioFile = new File(filepath, "shadow");
62 | if (!audioFile.exists())
63 | audioFile.mkdirs();
64 | }
65 |
66 | private void onRecording() {
67 | list.add(shortToByte(buffer, buffer.length));
68 | }
69 |
70 | private void onSave() {
71 | int size = list.size() * bufferSizeInBytes;
72 | ByteBuffer out = ByteBuffer.allocate(size * 2);
73 | for (byte[] b : list) {
74 | out.put(b);
75 | }
76 | list.clear();
77 | saveAudio(out.array());
78 | }
79 |
80 | public void doIt() {
81 | buffer = new short[bufferSizeInShorts];
82 | int bufferReadResult = audioRecorder.read(buffer, 0, bufferSizeInShorts);
83 | if (bufferReadResult != AudioRecord.ERROR_BAD_VALUE && AudioRecord.ERROR_INVALID_OPERATION != bufferReadResult) {
84 | int max = 0;
85 | for (short s : buffer) {
86 | if (Math.abs(s) > max) {
87 | max = Math.abs(s);
88 | }
89 | }
90 | level = max;
91 | if (level > voiceActivityLevel) {
92 | isVoiceActivityDetected = true;
93 | isRecording = true;
94 | timeDelayStart = System.currentTimeMillis();
95 | } if ((timeDelayStart + delayTime) < System.currentTimeMillis() && isVoiceActivityDetected) {
96 | onSave();
97 | isVoiceActivityDetected = false;
98 | isRecording = false;
99 | }
100 | if (isRecording) {
101 | onRecording();
102 | }
103 | }
104 | }
105 |
106 | private void saveAudio(byte[] finalBuffer) {
107 | String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
108 | String fn = audioFile.getAbsolutePath() + "/" + fileName + ".wav";
109 | FileOutputStream out;
110 | try {
111 | out = new FileOutputStream(fn);
112 | try {
113 | out.write(makeWawFileStructure(finalBuffer.length/2, finalBuffer));
114 | out.close();
115 | } catch (IOException e) {
116 | // TODO Auto-generated catch block
117 | e.printStackTrace();
118 | }
119 |
120 | } catch (FileNotFoundException e) {
121 | // TODO Auto-generated catch block
122 | e.printStackTrace();
123 | }
124 | }
125 |
126 | private byte[] makeWawFileStructure(int totalReadBytes, byte[] totalByteBuffer) {
127 | long totalAudioLen = 0;
128 | long totalDataLen = totalAudioLen + 36;
129 | long longSampleRate = RECORDER_SAMPLE_RATE;
130 | int channels = 1;
131 | long byteRate = RECORDER_BPP * RECORDER_SAMPLE_RATE * channels / 8;
132 | totalAudioLen = totalReadBytes;
133 | totalDataLen = totalAudioLen + 36;
134 | byte finalBuffer[] = new byte[totalReadBytes + 44];
135 |
136 | finalBuffer[0] = 'R'; // RIFF/WAVE header
137 | finalBuffer[1] = 'I';
138 | finalBuffer[2] = 'F';
139 | finalBuffer[3] = 'F';
140 | finalBuffer[4] = (byte) (totalDataLen & 0xff);
141 | finalBuffer[5] = (byte) ((totalDataLen >> 8) & 0xff);
142 | finalBuffer[6] = (byte) ((totalDataLen >> 16) & 0xff);
143 | finalBuffer[7] = (byte) ((totalDataLen >> 24) & 0xff);
144 | finalBuffer[8] = 'W';
145 | finalBuffer[9] = 'A';
146 | finalBuffer[10] = 'V';
147 | finalBuffer[11] = 'E';
148 | finalBuffer[12] = 'f'; // 'fmt ' chunk
149 | finalBuffer[13] = 'm';
150 | finalBuffer[14] = 't';
151 | finalBuffer[15] = ' ';
152 | finalBuffer[16] = 16; // 4 bytes: size of 'fmt ' chunk
153 | finalBuffer[17] = 0;
154 | finalBuffer[18] = 0;
155 | finalBuffer[19] = 0;
156 | finalBuffer[20] = 1; // format = 1
157 | finalBuffer[21] = 0;
158 | finalBuffer[22] = (byte) channels;
159 | finalBuffer[23] = 0;
160 | finalBuffer[24] = (byte) (longSampleRate & 0xff);
161 | finalBuffer[25] = (byte) ((longSampleRate >> 8) & 0xff);
162 | finalBuffer[26] = (byte) ((longSampleRate >> 16) & 0xff);
163 | finalBuffer[27] = (byte) ((longSampleRate >> 24) & 0xff);
164 | finalBuffer[28] = (byte) (byteRate & 0xff);
165 | finalBuffer[29] = (byte) ((byteRate >> 8) & 0xff);
166 | finalBuffer[30] = (byte) ((byteRate >> 16) & 0xff);
167 | finalBuffer[31] = (byte) ((byteRate >> 24) & 0xff);
168 | finalBuffer[32] = (byte) (2 * 16 / 8); // block align
169 | finalBuffer[33] = 0;
170 | finalBuffer[34] = RECORDER_BPP; // bits per sample
171 | finalBuffer[35] = 0;
172 | finalBuffer[36] = 'd';
173 | finalBuffer[37] = 'a';
174 | finalBuffer[38] = 't';
175 | finalBuffer[39] = 'a';
176 | finalBuffer[40] = (byte) (totalAudioLen & 0xff);
177 | finalBuffer[41] = (byte) ((totalAudioLen >> 8) & 0xff);
178 | finalBuffer[42] = (byte) ((totalAudioLen >> 16) & 0xff);
179 | finalBuffer[43] = (byte) ((totalAudioLen >> 24) & 0xff);
180 |
181 | for (int i = 0; i < totalReadBytes; ++i)
182 | finalBuffer[44 + i] = totalByteBuffer[i];
183 | return finalBuffer;
184 | }
185 |
186 | private byte[] shortToByte(short[] input, int elements) {
187 | int short_index, byte_index;
188 | int iterations = elements; //input.length;
189 | byte[] buffer = new byte[iterations * 2];
190 | short_index = byte_index = 0;
191 | for (/*NOP*/; short_index != iterations; /*NOP*/) {
192 | buffer[byte_index] = (byte) (input[short_index] & 0x00FF);
193 | buffer[byte_index + 1] = (byte) ((input[short_index] & 0xFF00) >> 8);
194 | ++short_index;
195 | byte_index += 2;
196 | }
197 | return buffer;
198 | }
199 |
200 | public void start() {
201 | audioRecorder.startRecording();
202 | }
203 |
204 | public void stop() {
205 | audioRecorder.stop();
206 | }
207 |
208 | public int getVoiceActivityLevel() {
209 | return level;
210 | }
211 |
212 | @Override
213 | public void setVoiceActivityLevel(int voiceActivityLevel) {
214 | this.voiceActivityLevel = voiceActivityLevel;
215 | }
216 |
217 | @Override
218 | public void setDelayTime(int delayTime) {
219 | this.delayTime = delayTime;
220 | }
221 |
222 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------