Attempting to record mic input over Bluetooth - java

I have an Arduino which broadcasts via Bluetooth, input from a mic.
I want to connect the phone so that it'll record and save the input from the Arduino mic via Bluetooth.
When I run the following code, I have a few issues.
I can't seem to find the file I saved.
File file=new File(mFilePath2,"test.txt");
On Logcat I'm getting the following errors when I run Bluetooth_Test()
ACDB-LOADER - Error: ACDB AudProc vol returned = -19
MediaPlayer - Error (1, -1004)
When I run stop() I get:
MPEG4Writer - Stop() called but track is not started
MediaPlayer-JNI QCMediaPlayer mediaplayer NOT present
MediaPlayer - Should have subtitle controller already set
I'm not sure what is happening and I'm not sure how to figure it out.
References:
Sony - Use Bluetooth for audio I/O
Media Player called in state 0, error (-38,0) (it solved one error, not listed above)
Code:
public void Bluetooth_Test (){
Toast.makeText(getActivity(), "weee", Toast.LENGTH_LONG).show();
maudioManager = (AudioManager) getActivity().getSystemService(getActivity().AUDIO_SERVICE);
// Switch to headset
maudioManager.setMode(AudioManager.MODE_IN_CALL); // to use headset's I/O and not phone's
// Start audio I/O operation (in background)
maudioManager.startBluetoothSco();
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // set source to current mic (should be Bluetooth)
mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String mFilePath2 = mFilePath;
mFilePath += "/youraudiofile.mp3";
File file=new File(mFilePath2,"test.txt");
// Set file extension for the recorded audio file
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// Set a file path for the recorded audio file
mRecorder.setOutputFile(mFilePath);
// Set encoding of the audio
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
}
catch (IOException e){
Log.e("Starting mRecorder", "IO Exception");
}
// Start recording
mRecorder.start();
}
public void stop () {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
mRecorder = null;
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mPlayer.start(); // Start playing audio file
}
});
// Audio file to be played
mPlayer.prepareAsync();
} catch (IOException e){
Log.e("Stop Function", "IO Exception");
}
}

Related

Outgoing call recording audio file has no sound

After recording an outgoing phone call, I am trying to play the recorded file - to make sure the call recording worked as expected (I am doing it using 'MediaPlayer'), but there is no sound.
So I tried to access the actual file on the phone (simply attached the phone to the computer and accessed it's files). When I played it the recording it was in the right length but again no sound.
What am I missing?
This is how I record the phone call:
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
File callAudioFile = null;
try {
File downloadsDir = context.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
callAudioFile = File.createTempFile("deTuCelRecord", ".amr", downloadsDir);
} catch (IOException e) {
e.printStackTrace();
}
assert callAudioFile != null;
audioFilePath = callAudioFile.getAbsolutePath();
recorder.setOutputFile(audioFilePath);
try {
recorder.setOnErrorListener(new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Log.e("MediaRecorder", "MediaRecorder error " + what + " " + extra);
}
});
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
This is the code which ends the call recording:
recorder.stop();
recorder.release();
This is how I play the audio file:
MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(audioFilePath);
mPlayer.prepare();
Toast.makeText(getApplicationContext(), "PLAYING AUDIO", Toast.LENGTH_LONG).show();
mPlayer.start();
Log.d("PLAY_AUDIO", "Started playing audio");
} catch (IOException e) {
Log.e("PLAY_AUDIO", "Failed to play audio");
}
Please check this Accessibilty Service in your testing phone.
If you are trying to record call on Android Q.
Please refer this link
You can try
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); It need Manifest.permission.CAPTURE_AUDIO_OUTPUT permission.
Please check AudioSource Source documentation for difference between VOICE_CALL and VOICE_COMMUNICATION
The issue was the android version - from android 10 it didn't allow me to record the call but on android 9 it did.

How to play video from MediaRecorder in Android

I want develop one screen recorder application
I develop this and i can record from screen, but after stop recording when i want play this video, show me this message :
Cannot play video. Unsupported file type
For record screen i used MediaProjectionManager, MediaProjection, MediaRecorder !
My codes :
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initRecorder() {
try {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
videoUri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ new StringBuilder("/Rec_").append(new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss").format(new Date()))
.append(".mp4").toString();
mediaRecorder.setOutputFile(videoUri);
mediaRecorder.setVideoSize(DISPLAY_WIDTH, DISPLAY_HEIGHT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setVideoEncodingBitRate(500 * 1000);
mediaRecorder.setVideoFrameRate(30);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int orientation = ORIENTATIONS.get(rotation + 90);
mediaRecorder.setOrientationHint(orientation);
mediaRecorder.prepare();
} catch (Exception e) {
}
}
Why not play my recorded videos? how can i fix it?

MediaRecorder not saving files

I've had a look through the other people's encounters with this problem and have not found an adequate solution.
Like them, I followed the tutorial on camera functionality at: http://developer.android.com/guide/topics/media/camera.html.
Everything listed below works perfectly to the point where I assume that the program has recorded video as I had intended. However, upon reviewing the video in the gallery, it has not appeared. I'm confused as there are no IOExceptions or other bugs present when connected for USB debugging. Strangely, upon removing the USB and plugging it in again, whenever that may be, either immediately or at some point days in the future, all of the previously recorded videos appear in the gallery. Clearly there something I have missed or some aspect of recording video that I am not aware of. Would appreciate any help or guidance, thank you.
Pertinent code is as follows, I'll post more if someone needs it.
Camera Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCamera = MainActivity.getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
button_capture = (Button) findViewById(R.id.button_capture);
button_capture.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
button_capture.setText("Capture");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
button_capture.setText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
});
}
private boolean prepareVideoRecorder(){
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
mMediaRecorder.setOutputFile(MediaCapture.getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
Media Capture:
public static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_VIDEO));
}
/**
* Create a File for saving an image or video
*/
public 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_MOVIES), "MyApplication");
// 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("MyApplication", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
I too was very perplexed by this behaviour until I realised unplugging the USB was causing the files to appear. This appears to be a bug in Android, possibly related to this one :
https://code.google.com/p/android/issues/detail?id=195362
Clearly, the file has been written correctly, but for some reason the new file is not visible. In any case, the solution/workaround offered in the link above is to force a media scan of your file. e.g.
MediaScannerConnection.scanFile(getContext(), new String[]{this.mediaFile.getAbsolutePath()}, null, null);
Where 'mediaFile' is the file your mediaRecorder has just finished writing. With this in place I do not need to unplug the USB cable to see the file and it appears immediately after recording has finished.
I am running Android 5.0.2 on a Samsung Galaxy A5. This feels more of a workaround than a fix and I can't be sure it will work on other devices or Android versions, but I hope it helps someone.

Media Playback of Recorded Audio not able to play on speaker on Android

I am making a Call recorder app in Android. I have a service that detects the incoming and outgoing call and as soon as the service detects the incoming or outgoing call it starts the recording through media player. It is getting recorded sucessfully but I am unable to play it on speaker. The volume is very low even after enabling speakers through Audio Manager. Please let me know where I might be going wrong.
Note: I am guessing that my audio is not getting recorded properly because if I play the recorded file through my phone music player, then even there I am not able to play that file on speaker.
below is my code which is used to start the recording:
try{
MediaRecorder mediaRecorder = new MediaRecorder();
if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_COMMUNICATION"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_UPLINK"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("VOICE_DOWNLINK"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("MIC"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
}
else if(AUDIO_SOURCE_TYPE.equalsIgnoreCase("DEFAULT"))
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
}
else
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
}
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(getTempFilename());
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaRecorder.start();
Below is the Media Playback Code :
final MediaPlayer mp=new MediaPlayer();
String uri= getIntent().getStringExtra("fileURI"); //fetches the string defining the path of file to be played
Uri fileURI = Uri.parse(uri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.setSpeakerphoneOn(true);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_PLAY_SOUND);
try{
try {
mp.setDataSource(getApplicationContext(), fileURI);
} catch (IOException e) {
e.printStackTrace();
}
}
mp.prepare();
}catch(Exception e){e.printStackTrace();}
mp.start();

File that I recorded with MediaRecorder can't be played

I'm using MediaRecoder to record sound, but after I'm done recording it can't be played. I tried with Google Play Music, ES Media Player, even uploaded it to pc and tried opening it with Winamp. Nothing plays it!
//AUDIO RECORDER
recorder = new MediaRecorder();
recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
externalOutputPath = externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/test.mp3";
recorder.setOutputFile(externalOutputPath);
}
else
{
storagePath = Environment.getDataDirectory().getAbsolutePath();
recorder.setOutputFile(storagePath + "/Android/data/com.whizzappseasyvoicenotepad/test.mp3");
}
Even tried opening it inside the application with button click:
public void testPlay (View v) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(externalOutputPath);
mediaPlayer.prepare();
mediaPlayer.start();
}
But that crashes the application. But that is not the main problem, the main problem is the fact that there's no way I can play the file. Is there something wrong with encoding or something?
I also tried to change it from .mp3 to .3gp and it didn't work. Then I also tried removing .mp3 and .3gp, leaving just 'test' as a name and then it didn't even recognize it as an audio file.
Oh, and if anyone wants the logcat when the application crashes:
07-31 16:51:43.953: E/AndroidRuntime(26918): java.lang.IllegalStateException: Could not execute method of the activity
07-31 16:51:43.953: E/AndroidRuntime(26918): Caused by: java.lang.reflect.InvocationTargetException
07-31 16:51:43.953: E/AndroidRuntime(26918): Caused by: java.io.IOException: setDataSourceFD failed.: status=0x80000000
But again, app crashing isn't the problem at the moment. First I want to solve the problem why the audio file can't be played. But if you have any idea why it crashes I would also appreciate it!
I'm still not sure what was the problem, but I think there was something wrong with the way I stopped recording (the whole try, catch thing). I just rewrote the whole code and put the MediaRecorder in two different methods. startRecording() and stopRecording() method. And now it works perfectly!
startRecording()
public void startRecording (){
recorder = new MediaRecorder();
recorder.reset();
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
externalStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
externalOutputPath = externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/test.mp3";
recorder.setOutputFile(externalOutputPath);
}
else
{
storagePath = Environment.getDataDirectory().getAbsolutePath();
recorder.setOutputFile(storagePath + "/Android/data/com.whizzappseasyvoicenotepad/test.mp3");
}
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
stopRecording()
public void stopRecording() {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}

Categories

Resources