Media recorder sound have poor quality - java

What i try to do is to record a sound after to upload it into firebase
and to retrieve then into reciclerview were i can control the
play/stop and the progress. Like whatsApp audio messages
The class AudioPlayer its called in the Main activity by pressing a
button and return the value to upload the file in firebase.Its work
but the sound quality its very poor and its work just in browser or
directly in source folder or i can t play it in other formats like
THREE_GPP just when i play it directly in the source folder.
public class StartRecordMessage extends AppCompatActivity implements Runnable {
private static String fileName = null;
private MediaRecorder myAudioRecorder;
private MediaPlayer player = null;
private boolean permissionToRecordAccepted = false;
private String[] permissions = {Manifest.permission.RECORD_AUDIO};
private final String TAG = "StartRecordMessageClass";
private String audioName = null;
private String externalStoragePath,externalOutputPath,storagePath;
public StartRecordMessage(MediaRecorder myAudioRecorder) {
this.myAudioRecorder = myAudioRecorder;
}
#Override
public void run() {
startRecording();
}
public String startRecording (){
myAudioRecorder = new MediaRecorder();
myAudioRecorder.reset();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
externalOutputPath = externalStoragePath + File.separator + "/Android/data/test.mp3";
myAudioRecorder.setOutputFile(externalOutputPath);
}
else
{
storagePath = Environment.getDataDirectory().getAbsolutePath();
myAudioRecorder.setOutputFile(storagePath + "/Android/data/test.mp3");
}
try {
Log.i(TAG, "--------------recording started confirmed" + externalOutputPath + storagePath );
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (externalOutputPath.isEmpty()){
return storagePath;
}else {
return externalOutputPath;
}
}
Follow method is in the main activity
#Override
public void onRecordingCompleted() {
Log.i(TAG, "---------completed");
startThread = new Thread(new StartRecordMessage(myAudioRecorder));
startThread.start();
startRecordMessage = new StartRecordMessage(myAudioRecorder);
audioMessage = startRecordMessage.startRecording();
Log.i(TAG, "recordingCompleted--------------" + audioMessage);
UploadSound(audioMessage);
}
messageListAdapter.notifyDataSetChanged();
}
AudioPlayerClass
public class AudioPlayer {
public static void play(Context ctx, String path) {
try {
final AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
final int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
final MediaPlayer mediaPlayer = MediaPlayer.create(ctx, Uri.parse(path));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (!audioManager.isWiredHeadsetOn()) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_VIBRATE);
}
mp.release();
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!audioManager.isWiredHeadsetOn()) {
int volume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) / 2;
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_VIBRATE);
}
mp.start();
}
});
} catch(
Throwable e)
{
Log.i("AudioUtil", "Unable to play: " + path, e);
}
}
}
AdapterClass
holder.playStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickCount++;
if (clickCount==1) {
isPlayng=true;
holder.playStop.setBackgroundResource(R.drawable.ic_pause);
Log.i(TAG,"audio url---------------" + audio);
audioPlayer = new AudioPlayer();
audioPlayer.play(context,audio);
Log.i(TAG, "Media player ------------"+ clickCount + " is play: " +isPlayng);
}
if (clickCount>1){
isPlayng=false;
clickCount=0;
holder.playStop.setBackgroundResource(R.drawable.ic_play);
Log.i(TAG, "Media player ------------" + clickCount + " is play: " + isPlayng);
}
}
});
The follow error is triggered when i want to play the sound. The class
Audio player class is called in Adapter class but the problem is the
url.
https://firebasestorage.googleapis.com/v0/b/chat-b18d3.appspot.com/o/Audio%.....
2020-11-12 22:59:44.739 2621-2621 I/AudioUtil: Unable to play: https://firebasestorage.googleapis.com/v0/b/chat-b18d3.appspot.com/o/Audio%.....
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object
android.content.Context.getSystemService(java.lang.String)' on a null
object reference
at com.example....ChatRecord.AudioPlayer.play(AudioPlayer.java:13)
at com.example.chatMapOriginal.Profile.Chat.MyGroups.GroupChatAdapter$1.onClick(GroupChatAdapter.java:137)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)

try add values in your media file.
exmaple.
// Setup values for the media file
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio file");
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();
// Construct uris
Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);
// Trigger broadcast to add
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
this code from here

Related

Empty file (0bytes) recorded by mediarecorder

I am trying to record a video in background through Service but my code creates and empty video file everytime and not returning any error as well.
Below is my Service class:
public class BackGroundVideoRecorder extends Service implements SurfaceHolder.Callback {
private static final String LOG_TAG = "BackGroundVideoRecorder";
private MediaRecorder mediaRecorder = null;
private WindowManager windowManager;
private SurfaceView surfaceView;
private Camera camera = null;
#Override
public void onCreate() {
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open(1);
mediaRecorder = new MediaRecorder();
camera.unlock();
//mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setCamera(camera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoSize(320, 480);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
String out = Environment.getExternalStorageDirectory() + "/Output/" +
DateFormat.format("yyyy-MM-dd_kk-mm-ss", new Date().getTime()) +
".mp4";
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "Output");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("FolderName", "failed to create directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
mediaRecorder.setMaxDuration(30000);
mediaRecorder.setOutputFile(mediaFile);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaRecorder.start();
}
// Stop recording and remove SurfaceView
#Override
public void onDestroy() {
if (camera != null) {
camera.lock();
camera.release();
}
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
}
if (windowManager != null) {
windowManager.removeView(surfaceView);
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Please suggest any solution or error if you found.
Thanks in advance.

Simple application of photo on Android Studio using Android tutorial of Camera

I want to create an application to take a picture. I followed the Camera tutorial, I tried 3 times but unable to make it work.I added a button to take a picture.But the app is not working properly.Please help me out.Here is my code:
// CAMERA VIEW displays the picture in a FrameLayout
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(0);
//get the holder and set this class as the callback, so we can get camera data here
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
//when the surface is created, we can set the camera to draw images in this surfaceholder
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
//before changing the application orientation, you need to stop the preview, rotate and then start it again
if(mHolder.getSurface() == null)//check if the surface is ready to receive camera data
return;
try{
mCamera.stopPreview();
} catch (Exception e){
//this will happen when you are trying the camera if it's not running
}
//now, recreate the camera preview
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//our app has only one screen, so we'll destroy the camera in the surface
//if you are unsing with more screens, please move this code your activity
mCamera.stopPreview();
mCamera.release();
}
}
And this is my activity, which takes a picture and save it
public class MainActivity extends Activity implements OnClickListener {
String TAG = "Main activity";
private Camera mCamera = null;
private CameraView mCameraView = null;
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// app en plein ecran
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// CREATION DU DYNAMIQUE
final Button menu = (Button) findViewById(R.id.buttonMenu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform action on click
Intent mainToMenu;
mainToMenu = new Intent(MainActivity.this, MenuActivity.class);
startActivity(mainToMenu);
}
});
try {
mCamera = Camera.open();//you can use open(int) to use different cameras
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
// quand j appuis sur un btn volume
final Button b = (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform action on click
mCamera.takePicture(null, null, mPicture);
}
});
}
public static final int MEDIA_TYPE_IMAGE = 1;
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FotoFoto");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}

how to recognize only loud voice (words) with pocketsphinx on android

I am building android app which have to listen all the time (constantly) a voice and catch a key word like eg help. I am using now MediaRecorder to get an amplitude, then if is loud (eg 20000), I call pocketsphinx speechrecognizer. The problem is that when speechrecognizer caught (or not) the key word I can't jump back to MediaRecorder, the app is crashed. Of course my app must work in the background (24 h/day) so my implementation is in Service, so my MediaRecorder is in separate thread.
I know that pocketsphinx can check also the amplitude (a scream), but how to make it? And is pocketsphinx (get amplitude) better solution to trigger the speech recognizer? Below my class, I would be very appreciate for any help.
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final class ServiceHandler extends Handler{
public ServiceHandler(Looper looper){
super(looper);
}
#Override
public void handleMessage(Message msg){
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/record.3gp";
getVoiceRecord();
}
}
#Override
public void onCreate() {
thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
//change to START_STICKY
Log.d("tag", "on start command");
Message msg = serviceHandler.obtainMessage();
msg.arg1 = startId;
serviceHandler.sendMessage(msg);
return Service.START_NOT_STICKY;
}
private void getVoiceRecord() {
startRecorder();
start = System.currentTimeMillis();
Log.d("tag", "Time started at " + start);
while (true){
if(recorder!=null){
amplitude = recorder.getMaxAmplitude();
if(amplitude>20000){
Toast.makeText(getApplicationContext(), "Scream detected",
Toast.LENGTH_LONG).show();
Log.d("tag", "Scream detected " + 20 * Math.log10(amplitude) + " amplitude: " + amplitude);
stopRecorder();
Log.d("tag", "Finish recording");
getSpeech();
}
finish = System.currentTimeMillis();
if(finish-start>50000){
//loop = false;
stopRecorder();
Log.d("tag", "Finish recording");
if(recorder==null){
recorder.reset();
startRecorder();
start = System.currentTimeMillis();
}
}
}
}//end of while loop
}
private void getSpeech() {
try {
Assets assets = new Assets(ScreamService.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
//return e;
}
reset();
}
private void stopRecorder() {
try{
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
Log.d("tag", "Stop recording");
}catch (IllegalStateException e) {
e.printStackTrace();
Log.d("tag", "Media Recorder did not stop " + e);
try {
Thread.sleep(2000);
recorder.stop();
recorder.release();
recorder = null;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}catch (RuntimeException e) {
e.printStackTrace();
Log.d("tag", "Media Recorder did not stop " + e);
}
}
private void startRecorder() {
Log.d("tag", "Start recording... ");
try {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(outputFile);
recorder.prepare();
recorder.start();
} catch (IOException e) {
e.printStackTrace();
Log.d("tag", "Media Recorder did not start IOExeption " + e);
} catch (IllegalStateException e) {
e.printStackTrace();
Log.d("tag", "Media Recorder did not start Ilegal State Trace" + e);
}
}
#Override
public void onDestroy() {
super.onDestroy();
recognizer.cancel();
recognizer.shutdown();
Toast.makeText(this, "Scream Service & recognizer Stopped.", Toast.LENGTH_SHORT).show();
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
String text = hypothesis.getHypstr();
//makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
Log.d("tag", "onResult " + text);
if(text.equals("help") || text.equals("help me")) {
recognizer.stop();
recognizer.cancel();
this.startService(new Intent(this, SendMessage.class));
getVoiceRecord();
}
}else {
Log.d("tag", "onResult is null");
}
}
#Override
public void onBeginningOfSpeech() {
//Log.d("tag", "onBeginningOfSpeech ");
}
#Override
public void onEndOfSpeech() {
counter++;
if(counter>5){
//recognizer.stop();
recognizer.cancel();
counter=0;
getVoiceRecord();
Log.d("tag", "Speech recognizer is killed");
}else {
//Log.d("tag", "onEndOfSpeech ");
reset();
}
}
private void reset() {
recognizer.stop();
recognizer.startListening("menu");
}
private void setupRecognizer(File assetsDir) throws IOException {
Log.d("tag", "default setup");
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// To disable logging of raw audio comment out this call (takes a lot of space on the device)
.setRawLogDir(assetsDir)
// Threshold to tune for keyphrase to balance between false alarms and misses
.setKeywordThreshold(1e-45f)
// Use context-independent phonetic search, context-dependent is too slow for mobile
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
// Create grammar-based search for selection between demos
File menuGrammar = new File(assetsDir, "menu.gram");
recognizer.addGrammarSearch("menu", menuGrammar);
}
#Override
public void onError(Exception error) {
Log.d("tag", "error "+error.getMessage());
}
#Override
public void onTimeout() {
Log.d("tag", "onTimeout");
}
You can modify pocketsphinx sources to compute amplitude of recorded audio data before you pass it into recognizer. In SpeechRecognizer.java RecognizerThread class:
.........
while (!interrupted()
&& ((timeoutSamples == NO_TIMEOUT) || (remainingSamples > 0))) {
int nread = recorder.read(buffer, 0, buffer.length);
if (-1 == nread) {
throw new RuntimeException("error reading audio buffer");
} else if (nread > 0) {
// int max = 0;
// for (int i = 0; i < nread; i++) {
// max = Math.max(max, Math.abs(buffer[i]));
// }
// Log.e("!!!!!!!!", "Level is: " + max);
// You can decide to skip buffer here
decoder.processRaw(buffer, nread, false, false);
......

How to record phone calls in Android

I am developing an application which can record calls in Android. I have read a lot of topics where the call recording problem was discussed. And i know that not all Android phones can record calls. But i am wondering how can record calls the most popular applications on Play Market, such as https://play.google.com/store/apps/details?id=com.appstar.callrecorder or https://play.google.com/store/apps/details?id=polis.app.callrecorder. I think that thy are using not on MediaRecorder class to do this job, but also something else. Because i have developed my own application, but i can record only my voice. But these two applications are recording both my voice and the voice of a man to whom i am calling. How they are doing this? I know that we can't get an access to device speaker to record sound from it. Could you give me some ideas of how to record voice calls? Here is my code that i am using in my application:
public class CallRecorderService extends Service {
private MediaRecorder mRecorder;
private boolean isRecording = false;
private PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stopRecording();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
startRecording(incomingNumber);
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
default:
break;
}
}
};
#Override
public void onCreate() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void startRecording(String number) {
try {
String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
savePath += "/Recorded";
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
savePath += "/record_" + System.currentTimeMillis() + ".amr";
mRecorder = new MediaRecorder();
SharedPreferences sPrefs = getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE);
int inputSource = sPrefs.getInt(Constants.SOURCE_INPUT, Constants.SOURCE_VOICE_CALL);
int outputSource = sPrefs.getInt(Constants.SOURCE_OUTPUT, Constants.OUTPUT_MPEG4);
switch (inputSource) {
case Constants.SOURCE_MIC:
increaseSpeakerVolume();
break;
}
mRecorder.setAudioSource(inputSource);
mRecorder.setOutputFormat(outputSource);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(savePath);
mRecorder.prepare();
mRecorder.start();
isRecording = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void stopRecording(){
if (isRecording) {
isRecording = false;
mRecorder.stop();
mRecorder.release();
}
}
private void increaseSpeakerVolume(){
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audio.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL,
AudioManager.ADJUST_RAISE,
AudioManager.FLAG_SHOW_UI);
}
}
I think they do use MediaRecorder. Perhaps main problem with it is that, it is tricky to write the data from it into something else but file on local store. In order to work it around, you could create a pipe. Then use its file descriptor as an input fd for MediaRecorder. And the pipe output then could be controlled by some thread that will read the audio packages (in one of format, aac or.. wav even) and then do whatever you want with the data.
Here is some code. Note, this is a proto, may not even compile, just to give you an idea.
/* 2M buffer should be enough. */
private final static int SOCKET_BUF_SIZE = 2 * 1024 * 1000;
private void openSockets() throws IOException {
receiver = new LocalSocket();
receiver.connect(new LocalSocketAddress("com.companyname.media-" + socketId));
receiver.setReceiveBufferSize(SOCKET_BUF_SIZE);
sender = lss.accept();
sender.setSendBufferSize(SOCKET_BUF_SIZE);
}
private void closeSockets() {
try {
if (sender != null) {
sender.close();
sender = null;
}
if (receiver != null) {
receiver.close();
receiver = null;
}
} catch (Exception ignore) {
}
}
public void prepare() throws IllegalStateException, IOException {
int samplingRate;
openSockets();
if (mode == MODE_TESTING) {
samplingRate = requestedSamplingRate;
} else {
samplingRate = actualSamplingRate;
}
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
try {
Field name = MediaRecorder.OutputFormat.class.getField("AAC_ADTS");
if (BuildConfig.DEBUG)
Log.d(StreamingApp.TAG, "AAC ADTS seems to be supported: AAC_ADTS=" + name.getInt(null));
mediaRecorder.setOutputFormat(name.getInt(null));
} catch (Exception e) {
throw new IOException("AAC is not supported.");
}
try {
mediaRecorder.setMaxDuration(-1);
mediaRecorder.setMaxFileSize(Integer.MAX_VALUE);
} catch (RuntimeException e) {
Log.e(StreamingApp.TAG, "setMaxDuration or setMaxFileSize failed!");
}
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioSamplingRate(samplingRate);
mediaRecorder.setOutputFile(sender.getFileDescriptor());
startListenThread(receiver.getInputStream());
mediaRecorder.start();
}

Capture image in portrait but get an ouput of landscape in directory

I am making my own camera in android, then whenever I capture images the images orientation is okay. but when i open it in my external sdcard file it is like that:
this is my code:
public class CameraApp extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "IMG_";
private static final String IMAGE_FOLDER = "/PhoneController/";
private static final String EXTENTION = ".jpg";
private String pictureName = "";
public String picNameToshare = "";
static final int FOTO_MODE = 0;
String speed;
String imageFilePath;
private Handler mHandler = new Handler();
public static String imageFilePath1;
FileOutputStream fos = null;
public Bitmap framebmpScaled;
public Bitmap SelecedFrmae;
public static Bitmap mergeBitmap;
public static Bitmap bmpfULL;
Camera camera;
Button button;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.camera);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
Handler myHandler = new Handler();
if (previewing) {
camera.stopPreview();
previewing = false;
Log.e("", "one");
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
myHandler.postDelayed(mMyRunnable, 2000); // called after 5
// seconds
button.setText("Waiting...");
Log.e("", "two");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Handler myHandler = new Handler();
* myHandler.postDelayed(mMyRunnable, 5000); // called after 5
* seconds button.setText("Waiting...");
*/
}
};
private Runnable mMyRunnable = new Runnable() {
public void run() {
Camera.Parameters params = camera.getParameters();
params.set("rotation", 90);
camera.setParameters(params);
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
storePicture(mergeBitmap);
button.setText("Capture");
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Display display = getWindowManager().getDefaultDisplay();
final int ScreenWidth = display.getWidth();
final int ScreenHeight = display.getHeight();
Log.e("" + display.getWidth(), "" + display.getWidth());
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap bmpScaled1 = Bitmap.createScaledBitmap(bitmapPicture,
ScreenWidth, ScreenHeight, true);
mergeBitmap = bmpScaled1;
showPicture();
}
};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setDisplayOrientation(90);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
void storePicture(Bitmap bm) {
mHandler.post(new Runnable() {
public void run() {
// showPicture();
}
});
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
.format(new Date());
this.pictureName = TAG + timeStamp;
picNameToshare = this.pictureName;
this.imageFilePath = IMAGE_FOLDER + this.pictureName + EXTENTION;
this.imageFilePath = sanitizePath(this.imageFilePath);
try {
checkSDCard(this.imageFilePath);
fos = new FileOutputStream(this.imageFilePath);
if (fos != null) {
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
fos.close();
}
} catch (IOException ioe) {
Log.e(TAG, "CapturePicture : " + ioe.toString());
} catch (Exception e) {
Log.e(TAG, "CapturePicture : " + e.toString());
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
imageFilePath1 = this.imageFilePath;
}
/**
* Check the SDCard is mounted on device
*
* #param path
* of image file
* #throws IOException
*/
void checkSDCard(String path) throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Toast.makeText(this,
"Please insert sdcard other wise image won't stored",
Toast.LENGTH_SHORT).show();
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording is exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
please help me.
Try using this
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);

Categories