My Problem is, that I capture audio by pressing the record button, but I can't see any audioFile in the specific path.
I capture sound, when I press the capture button:
private void startRecord()
{
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.VISIBLE);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//mediaRecorder.setOutputFormat(sound);
//mediaRecorder.setOutputFile(soundFilePath);
//mediaRecorder.setAudioEncoder(audioEncoder);
//Log.d("hier ", "hier" + soundFilePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
}catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Aufnahme gestartet", Toast.LENGTH_LONG).show();
}
When I press the Stop Recording Button the file should be saved in the specific path. I tried it with Directory Musik and Downloads, but I can't find any file there
final OnClickListener soundRecordStop = new OnClickListener(){
#Override
public void onClick(View v) {
soundStop();
}
};
public void soundStop(){
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Timestamp time = new Timestamp(System.currentTimeMillis());
String actualTime = sdf.format(time);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("soundformat", "format");
int audioEncoder = sharedPreferences.getInt("audioEncoder", Property.getAudioEncoderInt());
String dateiendung = ".aac";
int sound = 6;
if(name == "aac"){
dateiendung = ".aac";
sound = 6;
} else if(name == "amr_nb"){
dateiendung = ".3gp";
sound = 3;
}
else if( name == "amr_wb"){
dateiendung = ".3gp";
sound = 4;
}
else if( name == "default" ){
dateiendung = ".default";
sound = 0;
}
else if( name == "mpeg"){
dateiendung = ".mp4";
sound = 2;
}
else if( name == "gpp" ){
Log.d("in gpp", "in gpp");
dateiendung = ".3gp";
sound = 1;
}
soundFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
soundFilePath = soundFile.getAbsolutePath() + actualTime + dateiendung;
Log.d("hier ", "hier1" + mediaRecorder);
if(mediaRecorder != null){
Log.d("hier ", "hier2" + mediaRecorder);
try {
//mediaRecorder.prepare();
mediaRecorder.stop();
mediaRecorder.release();
//mediaRecorder = null;
Log.d("hier ", "hier4" + mediaRecorder);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mediaRecorder.setOutputFormat(sound);
mediaRecorder.setOutputFile(soundFilePath);
Log.d("hier ", "hier2");
String pfad = soundFile.getAbsolutePath();
Toast.makeText(getApplicationContext(), "Aufnahme in " + pfad + " gespeichert", Toast.LENGTH_LONG).show();
ImageButton soundStop = (ImageButton)findViewById(R.id.soundstop);
soundStop.setVisibility(View.INVISIBLE);
}
The path seems to be correct: pfad /storage/sdcard0/Download17.07.2014 11:55:58.aac
Thanks for the comment the missing File Separator wasn't intentionally. I insert the missing Separator in Order to save the audio File in Downloads Directory. But no File nevertheless 😑
Please help me to find my file ;)
Related
I'm developing an app using bass audio library. about voice change function, I can play audio succeessfully like this,
however , I cannot save it to custom file:
BASS.BASS_MusicFree(chan);
BASS.BASS_StreamFree(chan);
if ((chan = BASS.BASS_StreamCreateFile(new BASS.Asset(getAssets(), "test.mp3"), 0, 0, BASS.BASS_MUSIC_DECODE)) == 0
&& (chan = BASS.BASS_MusicLoad(new BASS.Asset(getAssets(), "test.mp3"), 0, 0, BASS.BASS_SAMPLE_LOOP | BASS.BASS_MUSIC_RAMP | floatable, 1)) == 0) {
// whatever it is, it ain't playable
((Button) findViewById(R.id.open)).setText("press here to open a file");
Error("Can't play the file");
return;
}
chan = BASS_FX.BASS_FX_TempoCreate(chan, BASS.BASS_SAMPLE_MONO);//enable pitch
chanFX = BASS_FX.BASS_FX_TempoGetSource(chan);
((Button) findViewById(R.id.open)).setText("test");
setupFX(mPitch, mRate, mIdistortionListener);
BASS.BASS_ChannelPlay(chan, false);
BASS.BASS_SetVolume(0.9f);
I'm developing an app using bass audio library. about voice change function,
however , I cannot save it to custom file:
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String path = testPath();
savePath(path);
Toast.makeText(TextActivity.this, "save successfully" + path, Toast.LENGTH_SHORT).show();
}
});
private String testPath() {
File localFile = new File(Environment.getExternalStorageDirectory().getPath(), "testVoid");
if (!localFile.exists()) {
localFile.mkdirs();
}
String path = localFile.getAbsolutePath() + "/record" + ".wav";
Log.d("mvn", path);
return path;
}
public void savePath(String filePath) {
long len = BASS.BASS_ChannelGetLength(chan, BASS.BASS_POS_BYTE);
double time = BASS.BASS_ChannelBytes2Seconds(chan, len);
File localFile = new File(filePath);
//flag=262208
if ((!isEmpty(filePath)) && (chan != 0) && (BASSenc.BASS_Encode_Start(chan, filePath, 262208, null, Integer.valueOf(0)) != 0)) {
int i1;
try {
ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(20000);
do {
i1 = BASS.BASS_ChannelGetData(chan, localByteBuffer, localByteBuffer.capacity());
} while ((i1 != -1) && (i1 != 0));
return;
} catch (Exception localException) {
localException.printStackTrace();
}
}
}
I am trying to merge mp4 and mp3 on Android, I am using the JavaCV, please check my code below first, then I explained the strange error after:
private void test2() throws Exception {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath();
int testId = 4;
String videoPath = path + "/" + "sample" + testId + ".mp4";
String audioPath = path + "/" + "love.mp3";
String outputPath = path + "/" + "out" + testId + ".mp4";
FrameGrabber grabber1 = new FFmpegFrameGrabber(videoPath);
FrameGrabber grabber2 = new FFmpegFrameGrabber(audioPath);
grabber1.start();
grabber2.start();
FrameRecorder recorder = new FFmpegFrameRecorder(outputPath,
grabber1.getImageWidth(), grabber1.getImageHeight(),
grabber2.getAudioChannels());
double frameRate = grabber1.getFrameRate();
recorder.setFrameRate(frameRate);
recorder.setSampleRate(grabber2.getSampleRate());
recorder.setVideoQuality(1);
recorder.start();
Frame frame1, frame2 = null;
// getLengthInTime is correct, but getLengthInFrames not accurate.
Log.d(TAG, " Video lengthInTime:" + grabber1.getLengthInTime()
+ " Video frames:" + grabber1.getLengthInFrames());
// Record video.
int count = 0;
while (true) {
frame1 = grabber1.grabFrame();
if (frame1 == null) {
break;
}
frame1.samples = null;
recorder.record(frame1);
count++;
Log.d(TAG, "Video frame timestamp:" + grabber1.getTimestamp());
}
Log.d(TAG, " Video frame count:" + count);
// Record audtio.
long videoTimestamp = recorder.getTimestamp();
while (true) {
frame2 = grabber2.grabFrame();
if (frame2 != null && grabber2.getTimestamp() <= videoTimestamp) {
frame2.image = null;
recorder.record(frame2);
// Log.d(TAG, "Audio frame timestamp:" +
// grabber2.getTimestamp());
} else {
break;
}
}
// release
recorder.stop();
recorder.release();
grabber1.stop();
grabber2.stop();
}
The output's audio is OK, but the video is strangle. The video play 1s and stop 1s, then repeat like this. The input video I recorded by Phone's camera.
I tried to count the real number of video frames, and I found the real number is much bigger than the number got from method getLengthInFrames().
frameGrabber grabs both ImageFrames and Sound Frames
if you need to work on VideoFrames or its count, Do like this
Frame grabFrame = frameGrabber.grabFrame();
if (grabFrame == null) {
// all frames are processed
System.out.println("!!! Failed cvQueryFrame");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RecordActivity.this, "Done !!!", Toast.LENGTH_SHORT).show();
}
});
break;
}
if (grabFrame.image != null) {
//This is a video Frame, Do your work here
}
}
String gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
mTextureView = (TextureView) findViewById(R.id.textureView1);
mTextureView.setSurfaceTextureListener(this);
final Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
final Button buttonCapturePreview = (Button)findViewById(R.id.Capturecamerapreview);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbFemale);
PatientInfo = (EditText) findViewById(R.id.PatientName);
PatientInfo.setHint("Enter patient name");
PatientAge = (EditText) findViewById(R.id.Age);
PatientAge.setHint("Age");
PatientId = (EditText) findViewById(R.id.PatientId);
PatientId.setHint("Enter patient Id no:");
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera mCamera)
{
int imageNum = 0;
String Name = PatientInfo.getText().toString();
String Age = PatientAge.getText().toString();
String Id = PatientId.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Rname = "Raw"+s.toString() + "_img_"+ String.valueOf(imageNum)+".jpg";
Pname = "Proc"+s.toString()+ "_img_"+ String.valueOf(imageNum) +".jpg";
File imagesFolders = new File(Environment.getExternalStorageDirectory().toString() + "/" + Name + Age + gender +Id);
imagesFolders.mkdirs();
File output = new File(imagesFolders, Rname);
while (output.exists()){
imageNum++;
Rname = "Raw"+s.toString() + "_img_"+ String.valueOf(imageNum) +".jpg";
Pname = "Proc"+s.toString() + "_img_"+ String.valueOf(imageNum) +".jpg";
output = new File(imagesFolders, Rname);
}
callname ="/sdcard/"+ Name + Age + gender + Id +"/"+ Rname;
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close(); }
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.rdbMale:
if (checked)
gender= "M";
rdbFemale.setChecked(false);
break;
case R.id.rdbFemale:
if (checked)
gender = "F";
rdbMale.setChecked(false);
break;
}
}
This is a piece of code. Am trying to save the images in the folder after enter the details like name, age, gender. but if i am not entering any thing and just take the image it will save the image into a null folder. I dont want this to happen. When details are not entered it should not save the image any where and it should show a message like please enter the data. Can anyone help why it is saving the data yo a null folder
Use Validation bro.
if (edt.getText().toString().length() <= 0) {
edt.setError("Please Enter Name/Name Required.");
valid_name = null;
} else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
or refer this site:
http://chintankhetiya.wordpress.com/2013/05/29/edit-text-validation/
I calculate decibels using the formula double dB = 20 * Math.log10(p/p0);
p = recorder.getMaxAmplitude()/51805.5336;
p0 = 0.0002;
But what this class does is representing the sound amplitude in a scale between 40 to 70, and it goes to 70 (maximum value) very easily, just tapping my fingers on the device.
final Runnable updater = new Runnable(){
public void run(){
updateTv();
};
};
final Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textView1);
tv.setText("Start");
startRecording();
if (runner == null)
{
runner = new Thread(){
public void run()
{
while (runner != null)
{
try
{
Thread.sleep(500);
Log.i("Noise", "Tock");
} catch (InterruptedException e) { };
mHandler.post(updater);
}
}
};
runner.start();
Log.d("Noise", "start runner()");
}
}
public void onResume()
{
super.onResume();
}
protected void updateTv() {
double decibel = Math.rint(100*getAmplitudeEMA())/100;
tv.setText("" + decibel + " dB");
AppLog.logString(Double.toString((getAmplitudeEMA())) + " dB");
}
private double getAmplitudeEMA() {
double p = getAmplitude()/51805.5336;
double p0 = 0.0002;
//mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
double mEMA2 = 20 * Math.log10(p/p0);
Log.i("MY", "" + recorder.getMaxAmplitude());
return mEMA2;
}
private double getAmplitude() {
if(recorder != null){
return recorder.getMaxAmplitude(); }
else
return 0;
}
private String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
AppLog.logString(filepath);
if(!file.exists()){
file.mkdirs();
}
AppLog.logString(file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}
private void startRecording(){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Actually in my app i have an EditText box and an TextView. In this EditText box whatever i write is stored in the file. So when i open my app again the stored text is shown in the TextView. All works fine for me. But whenever i change the language in Russian, the Keyboard that appear on click of EditText box contain Russian character. Now when i follow the same process of storing and reading the text that i entered, the while reading it read some garbage value and display in TextView instead of the text that i have stored. So my questions is why this happen only when i stored the text in other Language, because in storing the text in english language it works fine. The code that i have used while storing data into the file is shown below.
Write Notes into the file and register
public void writeNotesToFile(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// write notes count into the register
editor.putInt("notesCount", m_noteCount);
editor.commit();
// write notes to the file
SimpleDateFormat sdFormater = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
try
{
FileOutputStream writer = c.openFileOutput("Notes", Context.MODE_PRIVATE);
for (int i = 0; i < m_noteCount; i++)
{
String noteDate = sdFormater.format(m_arrNoteDate[i]);
writer.write(noteDate.getBytes());
writer.write(" ".getBytes());
writer.write(m_arrNoteString[i].getBytes());
writer.write("~`".getBytes());
}
writer.close();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
else
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
}
Read notes from the file and register
public void readNotesFromFile(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// Reads notes count from the register
m_noteCount = preferencesRead.getInt("notesCount", 0);
// Reads notes from file
String note = "";
char nextCharacter;
int count = 0, ch;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(file.exists())
{
try
{
FileInputStream fin = c.openFileInput("Notes");
while( (ch = fin.read()) != -1)
{
nextCharacter = (char)ch;
if (nextCharacter == '~')
{
ch = fin.read();
nextCharacter = (char)ch;
if (nextCharacter == '`')
{
int i=note.indexOf(" ");
String temp = note.substring(0, i);
try
{
m_arrNoteDate[count] = formatter.parse(temp);
}
catch (Exception e)
{
// To handle dates saved before the file was written in Local.US format.
// This code can be removed after few releases and all user have migrated.
SimpleDateFormat defFormatter = new SimpleDateFormat("dd-MMM-yyyy");
m_arrNoteDate[count] = defFormatter.parse(temp);
}
m_arrNoteString[count] = note.substring(i + 1);
count++;
note = "";
}
}
else
{
note = note + nextCharacter;
}
}
}
catch (Exception e)
{
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
}
}
}
}
Updated code that solve the problem
public void writeNotesToFile(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// write notes count into the register
editor.putInt("notesCount", m_noteCount);
editor.commit();
// write notes to the file
SimpleDateFormat sdFormater = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(!file.exists())
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
try
{
//convert to UTF format while Writing Data
FileOutputStream fos = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(fos, "UTF8");
// FileOutputStream writer = c.openFileOutput("Notes", Context.MODE_PRIVATE);
for (int i = 0; i < m_noteCount; i++)
{
String noteDate = sdFormater.format(m_arrNoteDate[i]);
writer.write(noteDate);
writer.write(" ");
writer.write(m_arrNoteString[i]);
writer.write("~`");
}
writer.close();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
else
{
try
{
file.createNewFile();
}
catch (Exception e)
{
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
}
public void readNotesFromFile(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// Reads notes count from the register
m_noteCount = preferencesRead.getInt("notesCount", 0);
// Reads notes from file
String note = "";
char nextCharacter;
int count = 0, ch;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
File file = c.getFileStreamPath("Notes");
if (m_noteCount > 0)
{
if(file.exists())
{
try
{
//convert to UTF format while Reading Data
FileInputStream fis = new FileInputStream(file);
InputStreamReader fin = new InputStreamReader(fis, "UTF8");
// FileInputStream fin = c.openFileInput("Notes");
while( (ch = fin.read()) != -1)
{
nextCharacter = (char)ch;
if (nextCharacter == '~')
{
ch = fin.read();
nextCharacter = (char)ch;
if (nextCharacter == '`')
{
int i=note.indexOf(" ");
String temp = note.substring(0, i);
try
{
m_arrNoteDate[count] = formatter.parse(temp);
}
catch (Exception e)
{
// To handle dates saved before the file was written in Local.US format.
// This code can be removed after few releases and all user have migrated.
SimpleDateFormat defFormatter = new SimpleDateFormat("dd-MMM-yyyy");
m_arrNoteDate[count] = defFormatter.parse(temp);
}
m_arrNoteString[count] = note.substring(i + 1);
count++;
note = "";
}
}
else
{
note = note + nextCharacter;
}
}
}
catch (Exception e)
{
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
}
}
}
}