I am developing an Android application that converts morse code to sounds and flashes. The flashes part works well, but I'm having troubles with sound part.
here is the code I have so far:
SoundPool sp =new SoundPool.Builder().setMaxStreams(1).build(); // declare before onCreate()
int soundId = sp.load(this,R.raw.beep,1); // declared inside onCreate()
public void flashCode(View view){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},0);
}
}
int dotTime=150; // in milliseconds
long ms=System.currentTimeMillis();
long ms2=System.currentTimeMillis();
//
//int streamID=mSoundPool.load(this,R.raw.beep,1);
for (int i=0;i<code.length();i++)
{
streamID=sp.play(soundId,1,1,1,1,1.0f);
sp.pause(streamID);
if (String.valueOf(code.charAt(i)).contentEquals("."))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime;
camManager.setTorchMode(cameraId, true);
//mSoundPool.resume(streamID);
while (ms<ms2){
ms=System.currentTimeMillis();
}
camManager.setTorchMode(cameraId, false);
//mSoundPool.stop(streamID);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (String.valueOf(code.charAt(i)).contentEquals("-"))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime*3;
camManager.setTorchMode(cameraId, true);
//mSoundPool.resume(streamID);
while (ms<ms2){
ms=System.currentTimeMillis();
}
camManager.setTorchMode(cameraId, false);
//mSoundPool.stop(streamID);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (String.valueOf(code.charAt(i)).contentEquals(" "))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime;
camManager.setTorchMode(cameraId, false);
while (ms<ms2){
ms=System.currentTimeMillis();
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
}
What I want is the play a sound when I turn flash on and off, but only during that time. I tried with SoundPool
but when I tested it out, the flash and sounds weren't synced and MediaPlayer
it even skipped some sounds.
Could you tell me what I'm doing wrong or tell me how would you do it.