package cilico.tools.barcode;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class CilicoSoundUtils {

	private final static int duration = 1; // seconds
	private final static int sampleRate = 2000;
	private final static int numSamples = duration * sampleRate;
	private final static double sample[] = new double[numSamples];
	private final static double freqOfTone = 1600; // hz
	private final static byte generatedSnd[] = new byte[2 * numSamples];

	public static void genTone() {
		// fill out the array
		for (int i = 0; i < numSamples; ++i) {
			sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone));
		}

		int idx = 0;
		for (double dVal : sample) {
			short val = (short) (dVal * 32767);
			generatedSnd[idx++] = (byte) (val & 0x00ff);
			generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
		}

	}

	@SuppressLint("NewApi")
	public static void playSound() {
		AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000,
				AudioFormat.CHANNEL_CONFIGURATION_MONO,
				AudioFormat.ENCODING_PCM_16BIT, numSamples,
				AudioTrack.MODE_STATIC);
		audioTrack.write(generatedSnd, 0, numSamples);
		audioTrack.play();
		try {
			Thread.sleep(30);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		audioTrack.release();

	}

	/**
	 * 成功声音 2014-5-9下午12:38:54
	 */
	public static void play() {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				genTone();
				playSound();
			}
		});
		thread.start();
	}

	/**
	 * 扫描按钮事件 2014-5-19下午3:17:19
	 * 
	 * @param keyCode
	 */
	public static void scanKeyDown(int keyCode) {
		if ((keyCode == 211 | keyCode == 212)) {
			Scanner.Read();
		}
	}

}
