AudioRecord not saving - java

I am trying to record the audio using AudioRecorde.
Though it creates file but could not record it. Please provide some inputs.
private void startRecording(){
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,44100,AudioFormat.CHANNEL_IN_MONO,AudioFormat.ENCODING_PCM_16BIT,AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
try {
recorder.startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
At the time of stoprecording
private void stopRecording(){
if(null != recorder){
recorder.stop();
recorder.release();
FileOutputStream fOut = null;
try{
int buffSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
//ByteBuffer buffer = ByteBuffer.allocate(AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT));
byte b[] = new byte[buffSize];
recorder.read(b,0,buffSize);
//getFilename() will get the file
fOut = new FileOutputStream(getFilename());
fOut.write(b);
}catch(Exception e){
e.printStackTrace();
}finally{
if(fOut != null){
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
recorder = null;
}
}
It creates a file with buffsize but could not play it.
Here is the code for playing the file
private void startPlaying() {
mPlayer = new MediaPlayer();
if(playing){
playing = false;
}else{
try {
File myFile = new File(prevFile);
txtStatus.setText("Playing...");
imgStatus.setVisibility(View.VISIBLE);
imgStatus.setBackgroundDrawable(getResources().getDrawable(R.drawable.play_small));
if(myFile.exists()){
System.out.println("file is exist");
}else{
System.out.println("file is not exist");
}
mPlayer.setDataSource(prevFile);
System.out.println("file path is is ::> " + prevFile);
mPlayer.prepare();
mPlayer.start();
playing = true;
} catch (IOException e) {
e.printStackTrace();
write.saveToFile(getApplicationContext(), "prepare() failed"+"\n");
}
}
}

Related

ObjectInputStream isn't finding any data to pull?

I am trying to read and write shape objects to a file for a drawing program, but when I try to read from the file it shows that the file is empty. The file is definitely being written to and updated, but when trying to read from the file it is showing that there are zero bytes available. The shape class is serializable so I am not sure why this isn't working at all.
public void writeToFile() {
try {
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for (Shape item : shapes) {
out.writeObject(item);
}
out.close();
fileOut.close();
System.out.println("Serialized data is saved in output.ser");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadFromFile() {
boolean cont = true;
Shape shape = null;
int count = 0;
while (cont) {
try {
FileInputStream fileIn = new FileInputStream("C:\\Users\\johnm\\eclipse-workspace\\CSE205_Assignment05\\save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
if (in.available() != 0) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
} else {
cont = false;
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Alright for some reason the .available() method isn't showing any bytes regardless of if there actually are any or not. To counter this I just threw in another try/catch statement where it continuously reads objects until it hits an EOFException and catches itself.
My code ended up looking like this once working.
public void loadFromFile() {
//** Loads set of shape objects from file
Shape shape = null;
int count = 0;
try {
FileInputStream fileIn = new FileInputStream("save.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(in.available() + " Bytes");
try {
while (true) {
shape = (Shape) in.readObject();
if (shape != null) {
shapes.add(shape);
count++;
} else {
System.out.println("Shape is null");
}
}
} catch (EOFException e) {
System.out.println("End of file exception");
}
in.close();
fileIn.close();
System.out.println("Deserialized " + count + " Objects");
repaint();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Read form ZipDecryptInputStream and write it to OutputStream

public void decrypt(String inputFile, String password) {
ZipDecryptInputStream zipDecrypt = null;
try {
zipDecrypt = new ZipDecryptInputStream(new FileInputStream(
inputFile), password);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File file = new File("outouttfile.tsv");
OutputStream fop = null;
try {
fop = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = zipDecrypt.read(buffer)) != -1) {
fop.write(buffer, 0, bytesRead);
System.out.println("Written");
}
} catch (IOException e) {
e.printStackTrace();
}
}
My while loop becomes an infinite loop and does not stop reading the file even its read once. Any idea why?

ftpClient wont upload,what am I missing?

Yeah, so I am using this code but whenever I run it, it doesnt upload anything. I have a similar code in another program the works perfect. What have I missed?
public void upload(){
new Thread(new Runnable() {
public void run() {
if (Looper.myLooper() == null)
{
Looper.prepare();
}
FTPClient ftpClient = new FTPClient();
FileInputStream inputStream = null;
int Upload = sharedPreferences.getInt("Upload", 1);
if (Upload == 1) {
try {
ftpClient.connect(InetAddress.getByName("XXX.net"));
ftpClient.login("XXX", "XXX");
ftpClient.changeWorkingDirectory("/public_html/Images/Cross");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
File file = new File(getApplicationInfo().dataDir + "/files/" + "temp" + ".jpg");
inputStream = new FileInputStream(file);
ftpClient.storeFile("temporary.jpg", inputStream);
file.delete();
ftpClient.logout();
ftpClient.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
...
}

merge audio and video file in android

i'm using mp4parser to merge audio and video files, here is below example i have tried but i'm getting null pointer exception at the very first line itself. i have kept audio and video files at desired location in my phone internal memory. if i debug, first line take lots of time & just halts after mins with null pointer error
try
{
H264TrackImpl h264Track = new H264TrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/video.mp4"));
AACTrackImpl aacTrack = new AACTrackImpl(new FileDataSourceImpl("/mnt/sdcard/myvideo/audio.acc"));
Movie movie = new Movie();
movie.addTrack(h264Track);
movie.addTrack(aacTrack);
Container mp4file = new DefaultMp4Builder().build(movie);
FileChannel fc = new FileOutputStream(new File("output.mp4")).getChannel();
mp4file.writeContainer(fc);
fc.close();
} catch (Exception ee)
{
Toast.makeText(this,ee.getMessage(),Toast.LENGTH_LONG).show();
}
whats wrong in my above code?
**Try this
I have follow few things to merge audio and video.
1)Capture Blank Video Dont use any audio source like
"mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);"
2)save it to the sd card
3)it does not support MIME type=mp3.
4)so if we have to merge video and video. audio must be mp4 or aac
.**
5)call the method on button click or On Crete
String audiopath = "/sdcard/audio.m4a";
String videopath = "/sdcard/video.mp4";
String outputpath = "/sdcard/output.mp4";
mux(video, audio, output);
6)Main Code is here pass it only path where you store your video, audio(m4a,aac),Output path.
public boolean mux(String videoFile, String audioFile, String outputFile) {
Movie video;
try {
video = new MovieCreator().build(videoFile);
} catch (RuntimeException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
Movie audio;
try {
audio = new MovieCreator().build(audioFile);
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
Track audioTrack = audio.getTracks().get(0);
video.addTrack(audioTrack);
Container out = new DefaultMp4Builder().build(video);
FileOutputStream fos;
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
BufferedWritableFileByteChannel byteBufferByteChannel = new BufferedWritableFileByteChannel(fos);
try {
out.writeContainer(byteBufferByteChannel);
byteBufferByteChannel.close();
Log.e("Audio Video", "11");
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static class BufferedWritableFileByteChannel implements WritableByteChannel {
// private static final int BUFFER_CAPACITY = 1000000;
private static final int BUFFER_CAPACITY = 10000000;
private boolean isOpen = true;
private final OutputStream outputStream;
private final ByteBuffer byteBuffer;
private final byte[] rawBuffer = new byte[BUFFER_CAPACITY];
private BufferedWritableFileByteChannel(OutputStream outputStream) {
this.outputStream = outputStream;
this.byteBuffer = ByteBuffer.wrap(rawBuffer);
Log.e("Audio Video", "13");
}
#Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is ok");
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
Log.e("Size ok ", "song size is not okssss ok");
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
#Override
public boolean isOpen() {
return isOpen;
}
#Override
public void close() throws IOException {
dumpToFile();
isOpen = false;
}
private void dumpToFile() {
try {
outputStream.write(rawBuffer, 0, byteBuffer.position());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

Starting and stopping music files in Java?

This is my sound class.
public class Sounds extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288;
enum Position {
LEFT, RIGHT, NORMAL
};
public Sounds(String wavFile) {
filename = wavFile;
curPosition = Position.NORMAL;
}
public Sounds(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println(".wav file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
And this is my ActionListener that I want to stop the music when the user clicks a button. The music plays on start up.
btnSound.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnSound.setVisible(false);
btnNoSound.setVisible(true);
new Sounds("Sounds/MenuMusic.wav").end();
}
});
I can get the music to play just fine, but I can't figure out how to stop it. I tried using .stop() and .end() but I was told they were deprecated. Anyone have any idea how I can do this? thanks.
You could use the clip class. This is my code for reading a .wav file and playing it:
try {
File file = new File(src); // src is the location of the file
AudioInputStream stream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
} catch (Exception e) {
e.printStackTrace();
}
That was, clip.stop() will stop the clip. To reset the clip, use clip.setFramePosition(0). Note that clip does not need to be closed, because if clip.close() is called after clip.start(), the clip will not play.
Hope that's what you were looking for!
EDIT: Scoping
Using scoping in Java, if you declare a local variable in a method, you cannot access it outside of the method. If you want to access the clip outside of the main method, extract it to a field:
class Main {
static Clip clip;
public static void main (String... args) {
try {
File file...
clip = AudioSystem.getClip();
...
} catch...
}
}

Categories