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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
|
public class WindEar { private static final String TAG = "rustApp"; private static final String TMP_FOLDER_NAME = "AnWindEar"; private static final int RECORD_AUDIO_BUFFER_TIMES = 1; private static final int PLAY_AUDIO_BUFFER_TIMES = 1; private static final int AUDIO_FREQUENCY = 44100;
private static final int RECORD_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_STEREO; private static final int PLAY_CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_STEREO; private static final int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecordThread aRecordThread; private volatile WindState state = WindState.IDLE; private File tmpPCMFile = null; private File tmpWavFile = null; private OnState onStateListener; private Handler mainHandler = new Handler(Looper.getMainLooper());
private static String cachePCMFolder;
private static String wavFolderPath;
private static WindEar instance = new WindEar();
private WindEar() {
}
public static WindEar getInstance() { if (null == instance) { instance = new WindEar(); } return instance; }
public void setOnStateListener(OnState onStateListener) { this.onStateListener = onStateListener; }
public static void init(Context context) {
cachePCMFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + TMP_FOLDER_NAME;
File folder = new File(cachePCMFolder); if (!folder.exists()) { boolean f = folder.mkdirs(); Log.d(TAG, String.format(Locale.CHINA, "PCM目录:%s -> %b", cachePCMFolder, f)); } else { for (File f : folder.listFiles()) { boolean d = f.delete(); Log.d(TAG, String.format(Locale.CHINA, "删除PCM文件:%s %b", f.getName(), d)); } Log.d(TAG, String.format(Locale.CHINA, "PCM目录:%s", cachePCMFolder)); }
wavFolderPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + TMP_FOLDER_NAME;
File wavDir = new File(wavFolderPath); if (!wavDir.exists()) { boolean w = wavDir.mkdirs(); Log.d(TAG, String.format(Locale.CHINA, "wav目录:%s -> %b", wavFolderPath, w)); } else { Log.d(TAG, String.format(Locale.CHINA, "wav目录:%s", wavFolderPath)); } }
public synchronized void startRecord(boolean createWav) { if (!state.equals(WindState.IDLE)) { Log.w(TAG, "无法开始录制,当前状态为 " + state); return; } try { tmpPCMFile = File.createTempFile("recording", ".pcm", new File(cachePCMFolder)); if (createWav) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd_HHmmss", Locale.CHINA); tmpWavFile = new File(wavFolderPath + File.separator + "r" + sdf.format(new Date()) + ".wav"); } Log.d(TAG, "tmp file " + tmpPCMFile.getName()); } catch (IOException e) { e.printStackTrace(); } if (null != aRecordThread) { aRecordThread.interrupt(); aRecordThread = null; } aRecordThread = new AudioRecordThread(createWav); aRecordThread.start(); }
public synchronized void stopRecord() { if (!state.equals(WindState.RECORDING)) { return; } state = WindState.STOP_RECORD; notifyState(state); }
public synchronized void startPlayPCM() { if (!isIdle()) { return; } new AudioTrackPlayThread(tmpPCMFile).start(); }
public synchronized void startPlayWav() { if (!isIdle()) { return; } new AudioTrackPlayThread(tmpWavFile).start(); }
public synchronized void stopPlay() { if (!state.equals(WindState.PLAYING)) { return; } state = WindState.STOP_PLAY; }
public synchronized boolean isIdle() { return WindState.IDLE.equals(state); }
private class AudioRecordThread extends Thread { AudioRecord aRecord; int bufferSize = 10240; boolean createWav = false;
AudioRecordThread(boolean createWav) { this.createWav = createWav; bufferSize = AudioRecord.getMinBufferSize(AUDIO_FREQUENCY, RECORD_CHANNEL_CONFIG, AUDIO_ENCODING) * RECORD_AUDIO_BUFFER_TIMES; Log.d(TAG, "record buffer size = " + bufferSize); aRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, AUDIO_FREQUENCY, RECORD_CHANNEL_CONFIG, AUDIO_ENCODING, bufferSize); }
@Override public void run() { state = WindState.RECORDING; notifyState(state); Log.d(TAG, "录制开始"); try { FileOutputStream pcmFos = new FileOutputStream(tmpPCMFile);
FileOutputStream wavFos = new FileOutputStream(tmpWavFile); if (createWav) { writeWavFileHeader(wavFos, bufferSize, AUDIO_FREQUENCY, aRecord.getChannelCount()); } aRecord.startRecording(); byte[] byteBuffer = new byte[bufferSize]; while (state.equals(WindState.RECORDING) && !isInterrupted()) { int end = aRecord.read(byteBuffer, 0, byteBuffer.length); pcmFos.write(byteBuffer, 0, end); pcmFos.flush(); if (createWav) { wavFos.write(byteBuffer, 0, end); wavFos.flush(); } } aRecord.stop(); pcmFos.close(); wavFos.close(); if (createWav) { RandomAccessFile wavRaf = new RandomAccessFile(tmpWavFile, "rw"); byte[] header = generateWavFileHeader(tmpPCMFile.length(), AUDIO_FREQUENCY, aRecord.getChannelCount()); Log.d(TAG, "header: " + getHexString(header)); wavRaf.seek(0); wavRaf.write(header); wavRaf.close(); Log.d(TAG, "tmpWavFile.length: " + tmpWavFile.length()); } Log.i(TAG, "audio tmp PCM file len: " + tmpPCMFile.length()); } catch (Exception e) { Log.e(TAG, "AudioRecordThread:", e); notifyState(WindState.ERROR); } notifyState(state); state = WindState.IDLE; notifyState(state); Log.d(TAG, "录制结束"); }
}
private static String getHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(Integer.toHexString(b)).append(","); } return sb.toString(); }
private class AudioTrackPlayThread extends Thread { AudioTrack track; int bufferSize = 10240; File audioFile = null;
AudioTrackPlayThread(File aFile) { setPriority(Thread.MAX_PRIORITY); audioFile = aFile; int bufferSize = AudioTrack.getMinBufferSize(AUDIO_FREQUENCY, PLAY_CHANNEL_CONFIG, AUDIO_ENCODING) * PLAY_AUDIO_BUFFER_TIMES; track = new AudioTrack(AudioManager.STREAM_MUSIC, AUDIO_FREQUENCY, PLAY_CHANNEL_CONFIG, AUDIO_ENCODING, bufferSize, AudioTrack.MODE_STREAM); }
@Override public void run() { super.run(); state = WindState.PLAYING; notifyState(state); try { FileInputStream fis = new FileInputStream(audioFile); track.play(); byte[] aByteBuffer = new byte[bufferSize]; while (state.equals(WindState.PLAYING) && fis.read(aByteBuffer) >= 0) { track.write(aByteBuffer, 0, aByteBuffer.length); } track.stop(); track.release(); } catch (Exception e) { Log.e(TAG, "AudioTrackPlayThread:", e); notifyState(WindState.ERROR); } state = WindState.STOP_PLAY; notifyState(state); state = WindState.IDLE; notifyState(state); }
}
private synchronized void notifyState(final WindState currentState) { if (null != onStateListener) { mainHandler.post(new Runnable() { @Override public void run() { onStateListener.onStateChanged(currentState); } }); } }
public interface OnState { void onStateChanged(WindState currentState); }
public enum WindState { ERROR, IDLE, RECORDING, STOP_RECORD, PLAYING, STOP_PLAY }
private void writeWavFileHeader(FileOutputStream out, long totalAudioLen, long longSampleRate, int channels) throws IOException { byte[] header = generateWavFileHeader(totalAudioLen, longSampleRate, channels); out.write(header, 0, header.length); }
private byte[] generateWavFileHeader(long pcmAudioByteCount, long longSampleRate, int channels) { long totalDataLen = pcmAudioByteCount + 36; long byteRate = longSampleRate * 2 * channels; byte[] header = new byte[44]; header[0] = 'R'; header[1] = 'I'; header[2] = 'F'; header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff); header[5] = (byte) ((totalDataLen >> 8) & 0xff); header[6] = (byte) ((totalDataLen >> 16) & 0xff); header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W'; header[9] = 'A'; header[10] = 'V'; header[11] = 'E'; header[12] = 'f'; header[13] = 'm'; header[14] = 't'; header[15] = ' '; header[16] = 16; header[17] = 0; header[18] = 0; header[19] = 0; header[20] = 1; header[21] = 0; header[22] = (byte) channels; header[23] = 0; header[24] = (byte) (longSampleRate & 0xff); header[25] = (byte) ((longSampleRate >> 8) & 0xff); header[26] = (byte) ((longSampleRate >> 16) & 0xff); header[27] = (byte) ((longSampleRate >> 24) & 0xff); header[28] = (byte) (byteRate & 0xff); header[29] = (byte) ((byteRate >> 8) & 0xff); header[30] = (byte) ((byteRate >> 16) & 0xff); header[31] = (byte) ((byteRate >> 24) & 0xff); header[32] = (byte) (2 * channels); header[33] = 0; header[34] = 16; header[35] = 0; header[36] = 'd'; header[37] = 'a'; header[38] = 't'; header[39] = 'a'; header[40] = (byte) (pcmAudioByteCount & 0xff); header[41] = (byte) ((pcmAudioByteCount >> 8) & 0xff); header[42] = (byte) ((pcmAudioByteCount >> 16) & 0xff); header[43] = (byte) ((pcmAudioByteCount >> 24) & 0xff); return header; } }
|