I'm building an audio recorder using MediaRecorder and I want to rename the created file
So my main steps are:
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats = MediaRecorder.OutputFormat.MPEG_4;
private String file_exts = AUDIO_RECORDER_FILE_EXT_MP4 ;
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() +
file_exts);
}
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();
}
}
private void stopRecording() {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
}
}
and in AudioRecorder folder it created with name "138672.mp4"
So, how to change that, i want to it created with name a.mp4(example)
you can use this code instead of your getFilename() method:
private String getFilename() {
File file = new File(Environment.getExternalStorageDirectory(), "a.mp4");
if (!file.exists()) {
file.mkdirs();
}
set this code in startRecording() method:
recorder.setOutputFile(file+"");
Related
I'm trying to create an app that queries a site of cat images, saves them to the android device if the JSON ID is unique, and then display them from the device in a slideshow format. Despite everything my AsyncTask doesn't seem to actually be executing. Debugger confirms a network connection is established and doesn't feed me back any errors so I have no idea what's wrong with my code. Hoping someone can help! Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CatImages req = new CatImages();
req.execute();
}
class CatImages extends AsyncTask<String, Integer, String> {
ArrayList<String> ids = new ArrayList<String>();
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
ids.add(id);
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String fromDoInBackground) {
super.onPostExecute(fromDoInBackground);
}
}
}
Try changing !=null to ==null in your second while loop.
Also you just need while(on) in your first while loop.
Let me know if anything changes.
I'm trying to build an app for school that queries a website full of random cat pictures and displays them on an emulated android TV. My code looks right, but when I run it I get the spinning wheel showing it's loading and nothing else. I'm not sure what exactly is missing, but hoping someone can point me in the right direction. Code is below:
package com.example.lab2;
import androidx.appcompat.app.AppCompatActivity;
import androidx.loader.content.AsyncTaskLoader;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.ProgressBar;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> ids = new ArrayList<String>();
class CatImages extends AsyncTask<String, Integer, String> {
ContextWrapper cw = new ContextWrapper(getApplicationContext());
Bitmap images;
String id;
ImageView imageView = findViewById(R.id.imageView);
ProgressBar progressBar = findViewById(R.id.progressBar);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
boolean on = true;
#Override
protected String doInBackground(String... strings) {
while(on == true) {
try {
URL url = new URL("https://cataas.com/cat?json=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"), 8);
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line + "\n");
}
String result = builder.toString();
JSONObject image = new JSONObject(result);
id = image.getString("id");
for (String element : ids) {
if (element.contains(id)) {
return null;
} else {
images = BitmapFactory.decodeStream(response);
File path = new File(directory, id + ".jpg");
FileOutputStream outputStream = new FileOutputStream(path);
images.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
ids.add(id);
}
}
for (int i = 0; i < 100; i++) {
try {
publishProgress(i);
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | JSONException e) {
return null;
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
for(String element : ids) {
if(element.contains(id)) {
File openedPic = new File(directory, id + ".jpg");
try {
Bitmap opener = BitmapFactory.decodeStream(new FileInputStream(openedPic));
imageView.setImageBitmap(opener);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
I have a soundboard app and am trying to enable the user to share the sounds from my res/raw folder. My code seems to properly create a folder and copy the resource into it. However, when trying to share, I always get an error from the external app. (e.g. gmail says: "Cannot attach file"). Can anyone please help?
The code:
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Pls {
public void sendAudio(Activity activity){
try {
String mediaPath = copyFiletoExternalStorage(R.raw.audio_file, "audiofile.mp3",activity);
Intent shareMedia = new Intent(Intent.ACTION_SEND);
shareMedia.setType("audio/*");
shareMedia.putExtra(Intent.EXTRA_STREAM, Uri.parse(mediaPath));
activity.startActivity(Intent.createChooser(shareMedia, "Select app"));
} catch (Exception e) {
Toast.makeText(activity.getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
private String copyFiletoExternalStorage(int resourceId, String resourceName,Activity activity){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/" + resourceName;
try{
InputStream in = activity.getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
Log.i("err",e.toString());
}
return pathSDCard;
}
}
First of all open camera and capture 10 second video after open next activity and list of audio file then click the audio file this time merge the audio and video but in this my code getting error when select audio in storage.
Activity
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;
import com.coremedia.iso.boxes.Container;
import com.googlecode.mp4parser.authoring.Movie;
import com.googlecode.mp4parser.authoring.Track;
import com.googlecode.mp4parser.authoring.builder.DefaultMp4Builder;
import com.googlecode.mp4parser.authoring.container.mp4.MovieCreator;
import com.wos.capturevideowithaudio.R;
import com.wos.capturevideowithaudio.adapter.AudioListAdapter;
import com.wos.capturevideowithaudio.utils.Constant;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
public class AudioMixing extends AppCompatActivity {
private ArrayList<String> audio;
private VideoView mVideoView;
private RecyclerView rvAudioFile;
private AudioListAdapter audioListAdapter;
private String musicUri, timeStamp;
private String[] array_spinnerLoad, files;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audiomixing);
initView();
}
private void initView() {
rvAudioFile = (RecyclerView) findViewById(R.id.rvAudioFile);
mVideoView = (VideoView) findViewById(R.id.video_view);
//Display Current Capture Video
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
timeStamp = bundle.getString("timeStamp");
musicUri = bundle.getString("uri");
mVideoView.setVideoURI(Uri.parse(musicUri));
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
mVideoView.start();
}
//Get All AudioList in Mobile Phone
audio = new ArrayList<>();
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
File sd = new File(path);
File[] sdDirList = sd.listFiles();
if (sdDirList != null) {
array_spinnerLoad = new String[sdDirList.length];
files = new String[sdDirList.length];
for (int i = 0; i < sdDirList.length; i++) {
array_spinnerLoad[i] = sdDirList[i].getName();
Log.d(Constant.TAG, "getAudioName = " + sdDirList[i].getName());
files[i] = sdDirList[i].getAbsolutePath();
Log.d(Constant.TAG, "getAudioName = " + sdDirList[i].getAbsolutePath());
}
audioListAdapter = new AudioListAdapter(getApplicationContext(), array_spinnerLoad);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
rvAudioFile.setLayoutManager(layoutManager);
rvAudioFile.setAdapter(audioListAdapter);
audioListAdapter.OnItemClickListener(new AudioListAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
String fileName = array_spinnerLoad[position];
String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/" + fileName;
MediaPlayer mediaPlayer = new MediaPlayer();
try {
FileInputStream is = new FileInputStream(filePath);
mediaPlayer.setDataSource(is.getFD());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
String root = Environment.getExternalStorageDirectory().toString();
String audio = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/" + fileName;
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "HelloCamera");
String video = mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4";
String output = root + "/" + "jd.mp4";
Log.e(Constant.TAG, "audio:" + audio + " video:" + video + " out:" + output);
mux(video, audio, output);
}
});
}
}
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();//In this Line Error java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.googlecode.mp4parser.BasicContainer.getBoxes
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();
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 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);
}
#Override
public int write(ByteBuffer inputBuffer) throws IOException {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
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);
}
}
}
}
Error
Process: com.wos.capturevideowithaudio, PID: 7162
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.googlecode.mp4parser.BasicContainer.getBoxes(java.lang.Class)' on a null object reference
at com.googlecode.mp4parser.authoring.container.mp4.MovieCreator.build(MovieCreator.java:48)
at com.googlecode.mp4parser.authoring.container.mp4.MovieCreator.build(MovieCreator.java:35)
at com.wos.capturevideowithaudio.activity.AudioMixing.appendTwoVideo(AudioMixing.java:154)
at com.wos.capturevideowithaudio.activity.AudioMixing$1.onItemClick(AudioMixing.java:142)
at com.wos.capturevideowithaudio.adapter.AudioListAdapter$ViewHolder.onClick(AudioListAdapter.java:60)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22285)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
I am trying to download image from internet and store it locally in some hidden folder where the images are not visible to the user in his/her gallery.
Here is my code to do so. The image is getting displayed only when the device is connected to internet. In other words the image is not getting saved in the device and it is throwing an exception.
Here is my ImageStorage class:
package com.example.adhish.downloadretriveimage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by appy-20 on 6/1/17.
*/
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory() ;
File folder = new File(sdcard.getAbsoluteFile(), ".test_directory");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.test_directory/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static boolean checkifImageExists(String imagename)
{
Bitmap b = null ;
File file = ImageStorage.getImage("/"+imagename+".jpg");
String path = file.getAbsolutePath();
if (path != null)
b = BitmapFactory.decodeFile(path);
if(b == null || b.equals(""))
{
return false ;
}
return true ;
}
}
and here is my MainActivity.java:
package com.example.adhish.downloadretriveimage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Bitmap b;
String imagename;
String imgurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
imagename="394968_538b_7";
imgurl="https://udemy-images.udemy.com/course/750x422/394968_538b_7.jpg";
if(ImageStorage.checkifImageExists(imagename))
{
File file = ImageStorage.getImage("/"+imagename+".jpg");
// File file = ImageStorage.getImage("https://udemy-images.udemy.com/course/750x422/394968_538b_7.jpg");
String path = file.getAbsolutePath();
if (path != null){
b = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(b);
}
} else {
new GetImages(imgurl, imageView, imagename).execute() ;
}
}
private class GetImages extends AsyncTask<Object, Object, Object> {
private String requestUrl, imagename_;
private ImageView view;
private Bitmap bitmap;
private FileOutputStream fos;
private GetImages(String requestUrl, ImageView view, String _imagename_) {
this.requestUrl = requestUrl;
this.view = view;
this.imagename_ = _imagename_;
}
#Override
protected Object doInBackground(Object... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Object o) {
if (!ImageStorage.checkifImageExists(imagename_)) {
view.setImageBitmap(bitmap);
ImageStorage.saveToSdCard(bitmap, imagename_);
}
}
}
}
I have already given the external storage read write permission in my Manifest.
I found the solution to this problem. I am storing the images in SQLite database and here is the code for it:
https://github.com/adhishlal/URL_to_DB_Image