I just started working on an audio recorder app. So far, the app can record audio and play it. My end goal is to be able to save multiple audio files to the device. How would I do this? Can I use SharedPreferences? I haven't been able to find anything.
public class MainActivity extends AppCompatActivity {
Button play;
Button stop;
Button record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Create a folder in your external storage and store each file with a timestamp appended to the name of the file.
You can list all the video / audio files stored in this folder and select which video / audio you want to play anytime.
Get all files
public void displayAllFilesInFolder() {
List<String> filepath = new ArrayList<String>();
if (!hasSDCard()) {
return;
}
File dir = new File(android.os.Environment.getExternalStorageDirectory() + "folderName");
if (!dir.exists()) {
return;
}
File listAllFiles[] = dir.listFiles();
if (listAllFiles != null) {
for (int i = 0; i < listAllFiles.length; i++) {
if (!listAllFiles[i].isDirectory()) {
filepath.add(listAllFiles[i].getAbsolutePath());
}
}
}
}
Check if SD is mounted
private boolean hasSDCard(){
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
return true;
}
else{
return false;
}
}
You're already saving it to a file:
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
You just need to add more logic to pick a filename that doesn't already exist.
Related
working in recording when i am record first time this working fine but second time is starting recording and when stop then recording then it crash nad give java.lang.IllegalStateException
i dont underswtand why
my code is
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String name = user.get(SessionManager.KEY_NAME);
String email = user.get(SessionManager.KEY_EMAIL);
// outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
_Start = (Button)findViewById(R.id.start);
_Stop =(Button)findViewById(R.id.stop);
_Send = (Button)findViewById(R.id.sendbtn);
_Play =(Button)findViewById(R.id.play);
_CountTimer =(TextView)findViewById(R.id.timer_view);
_ImgView =(ImageView)findViewById(R.id.imgView);
boolean exists = (new File(path)).exists();
if(!exists) {
new File(path).mkdirs();
}
else {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(path + audioname);
}
_CountTimer.setText("00:30");
final GumzoCounterClass timer = new GumzoCounterClass(30000, 1000);
_Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
try {
mRecorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mRecorder.start();
timer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
_ImgView.setVisibility(View.VISIBLE);
_Start.setVisibility(View.INVISIBLE);
_Play.setVisibility(View.INVISIBLE);
_Stop.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Start Recording", Toast.LENGTH_SHORT).show();
}
});
_Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_ImgView.setVisibility(View.INVISIBLE);
_Start.setVisibility(View.VISIBLE);
_Stop.setVisibility(View.INVISIBLE);
_Play.setVisibility(View.VISIBLE);
mRecorder.stop();
timer.cancel();
_CountTimer.setText("Stoped Recording");
Toast.makeText(getApplicationContext(), "Stop Recording", Toast.LENGTH_SHORT).show();
}
});
_Play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer m = new MediaPlayer();
// _Start.setEnabled(false);
try {
m.setDataSource(outputFile);
} catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
} catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
public class GumzoCounterClass extends CountDownTimer {
public GumzoCounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
_CountTimer.setText("Completed");
mRecorder.stop();
mRecorder.release();
}
#Override
public void onTick(long millisUntilFinished) {
_CountTimer.setText((millisUntilFinished / 1000) + "");
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
LoginManager.getInstance().logOut();
startActivity(new Intent(getApplicationContext(),Login_Activity.class));
finish();
}
Toast.makeText(MainActivity.this, "Logout User", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
My Logcate
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at user.example.com.myApp.MainActivity$2.onClick(MainActivity.java:95)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20262)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
help me please
Its because you are calling stop on a null object. You should check the state of your MediaRecorder before stopping
According to the official example from google you need to do the following when stop recording.
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
And releaseMediaRecorder() is look like,
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
// clear recorder configuration
mMediaRecorder.reset();
// release the recorder object
mMediaRecorder.release();
mMediaRecorder = null;
}
}
Online radio streaming in android not working with mediaplayer.setDataSource method
public class MainActivity extends Activity implements View.OnClickListener {
private final static String RADIO_STATION_URL = "http://tunein.com/radio/Hindi-Desi-Bollywood-Evergreen-Hits-s129208/";
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private Button buttonRecord;
private Button buttonStopRecord;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
buttonRecord = (Button) findViewById(R.id.buttonRecord);
buttonRecord.setOnClickListener(this);
buttonStopRecord = (Button) findViewById(R.id.buttonStopRecord);
buttonStopRecord.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
} else if (v == buttonRecord) {
recorderThread = new RecorderThread();
recorderThread.start();
buttonRecord.setEnabled(false);
buttonStopRecord.setEnabled(true);
} else if (v == buttonStopRecord) {
stopRecording();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
buttonRecord.setEnabled(true);
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
buttonRecord.setEnabled(false);
buttonStopRecord.setEnabled(false);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
buttonStopRecord.setEnabled(false);
buttonRecord.setEnabled(true);
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
I saw your code and immediately noticed something, the link you used isn't a direct link to the audio file you want to stream, it should look more like http://192.240.102.133:11454/stream which is the correct url instead of http://tunein.com/radio/Hindi-Desi-Bollywood-Evergreen-Hits-s129208 you could learn how to get the direct url's from tunein here: https://www.quora.com/How-do-I-get-a-streaming-URL-for-Tunein
I am working on an App that requires recording a audio
Here's my partial code
private MediaRecorder myAudioRecorder;
private String outputFile = null;
private Button start, stop, play;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
play = (Button) findViewById(R.id.button3);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myrecording.3gp";;
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void start(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
start.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
}
The above code threw IllegalStateException. I have every permission entered in AndroidManifest.xml , I am very sure there's nothing wrong in AndroidManifest.xml.
I have read several solution but none of them working. How can I solve this problem?
public void stop(View view) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio Recorded successfully", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void play(View view) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
MediaPlayer m = new MediaPlayer();
m.setDataSource(outputFile);
m.prepare();
m.start();
Toast.makeText(getApplicationContext(), "Audio Playing", Toast.LENGTH_LONG).show();
}
}
I have developed this small MediaRecorder application. I have 3 buttons- Play (for Start Recording), Pause (for stop recording), Max (for finding Max Amplitude). I Googled to get it correct, but nothing worked fine for me.
The problem is it always give me 0 for getMaxAmplitude.
Below is the code i am using. Can any one please help
public class MainActivity extends Activity {
Button play,pause, max;
String outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/myexampl.3gp";
MediaRecorder mrecorder=new MediaRecorder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button)findViewById(R.id.button1);
pause= (Button)findViewById(R.id.button2);
max = (Button)findViewById(R.id.button3);
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mrecorder.setOutputFile(outputFile);
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
mrecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mrecorder.start();
Toast.makeText(getApplicationContext(), "Starts Recording!",
Toast.LENGTH_SHORT).show();
}
});
pause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
mrecorder.stop();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mrecorder.release();
Toast.makeText(getApplicationContext(), "Stops Recording!",
Toast.LENGTH_SHORT).show();
}
});
max.setOnClickListener(new OnClickListener() {
int ampl=0;
#Override
public void onClick(View v) {
try {
ampl=mrecorder.getMaxAmplitude();
} catch (IllegalStateException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), String.valueOf(ampl),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I need help/pointer to doc/sample code on how to load multiple audio files from a specific folder on the SD card and have it play a random file back(i think i can figure out the last step if i could just figure out how to load multiple files). Here is my incredibly poorly written app so far, don't judge too harshly as I'm learning as I go.
public class zazenbox extends Activity implements OnClickListener{
File filecheck;
MediaPlayer player;
Button playerButton;
Integer var1;
String path1;
AlertDialog.Builder alertbox;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
demoLoad();
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop);
playerButton.setOnClickListener(this);
demoPlay();
}
#Override
public void onPause() {
super.onPause();
player.pause();
}
#Override
public void onStop() {
super.onStop();
player.stop();
}
private void demoLoad() {
dirfilecheck();
player = new MediaPlayer();
player.setLooping(true);
try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }
}
private void dirfilecheck() {
filecheck = new File(Environment.getExternalStorageDirectory() + "/zazenbox");
if(filecheck.exists() && filecheck.isDirectory()) {
// load files.
var1 = 1;
path1 = filecheck + "/bm10" + var1 + ".wav";
} else {
// create folder, dl sample loop, and instruct user how to add music/loops.
filecheck.mkdirs();
alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Please put loopable media in zazenbox on your sdcard.");
alertbox.setNeutralButton("Ok, I will.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please plug in your device now", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
}
}
private void demoPause() {
player.pause();
playerButton.setText(R.string.play);
}
private void demoStop() {
player.stop();
playerButton.setText(R.string.play);
}
private void demoPlay() {
player.start();
playerButton.setText(R.string.stop);
}
private void playPause() {
if(player.isPlaying()) {
demoStop();
//demoPause();
//player.release();
var1++;
path1 = filecheck + "/bm10" + var1 + ".wav";
/*try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }*/
//player.start();
//demoPlay();
} else {
//do stuff
demoPlay();
}
}
}
Memory is extremely limited on mobile devices, so you wouldn't want to load songs you're not going to play. So what you should do is find all of the audio files in that folder, and then choose one and THEN load and play it.
You just need to stop the current player and create a new instance.
MediaPlayer player = MediaPlayer.create(this, Uri.parse("Path/To/Media"));
player.start();
// change track
player.stop();
player = MediaPlayer.create(this, Uri.parse("New/Path/To/Media"));
player.start();