I am developing an application where I want to start recording voice on button click, and also want to start playing video in video view at the same time.
now the app works on android 4.2 and android 5.1 but does not work on the latest device like android 7.0.
Here is the code
public class MainActivity extends Activity
{
Button start,stop,play;
Boolean recording=false;
String press_value="exit";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
boolean let_start_recording=true;
ImageView startIV,profileIV;
boolean recording_is_in_progress=false;
VideoView vv ;
MediaPlayer mPlayer;
RelativeLayout mainRel;
///new media player
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startIV=(ImageView)findViewById(R.id.imageView1);
profileIV=(ImageView)findViewById(R.id.imageView3);
vv = (VideoView)findViewById(R.id.your_video_view);
mainRel=(RelativeLayout)findViewById(R.id.main_rel);
recording_is_in_progress=false;
StopAnimation();
profileIV.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(let_start_recording)
{
let_start_recording=false;
startIV.setImageResource(R.drawable.recorder_stop_circle);
startRecording();
recording_is_in_progress=true;
StartAnimation();
}
else
{
let_start_recording=true;
startIV.setImageResource(R.drawable.recorder_start_circle);
stopRecording();
recording_is_in_progress=false;
StopAnimation();//Stop Animation once we press button
}
}
});
//START & STOP Recording
startIV.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(let_start_recording)
{
let_start_recording=false;
startIV.setImageResource(R.drawable.recorder_stop_circle);
startRecording();
recording_is_in_progress=true;
StartAnimation();
}
else
{
let_start_recording=true;
startIV.setImageResource(R.drawable.recorder_start_circle);
stopRecording();
recording_is_in_progress=false;
StopAnimation();//Stop Animation once we press button
}
}
});
}//EOF Oncreate
//(((( START ANIMATION ))))
public void StartAnimation()
{
// vv.setVisibility(View.VISIBLE);
startIV.setVisibility(View.VISIBLE);
mainRel.setVisibility(View.VISIBLE);
profileIV.setVisibility(View.GONE);
//Video Loop
vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
vv.start(); //need to make transition seamless.
}
});
// Uri uri = Uri.parse(R.drawable.sheep_video);
Uri uri= Uri.parse("android.resource://com.pac.myapp/raw/sheep_video");
vv.setVideoURI(uri);
vv.requestFocus();
vv.start();
vv.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.sheep_video));
vv.setOnPreparedListener(new OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mp.setLooping(true);
/// showtoast("video compelted");
}
});
}
public void StopAnimation()
{
if(vv.isPlaying())
vv.stopPlayback();
//vv.setVisibility(View.INVISIBLE);
startIV.setVisibility(View.GONE);
mainRel.setVisibility(View.INVISIBLE);
profileIV.setVisibility(View.VISIBLE);
}
private String getFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists())
{
file.mkdirs();
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String filename = dateFormat.format(new Date());
filename="Voice "+filename+".wav";
return (file.getAbsolutePath() + File.separator + filename);
//return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".wav");
}
private void startRecording()
{
AudioSavePathInDevice = getFilename();
// Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
// CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void stopRecording()
{
mediaRecorder.stop();
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public void onBackPressed()
{
if(recording_is_in_progress=true)
{
//if(recorder!=null)
//stopRecording();
finish();
}
}
public void home(View v)
{
//Intent i=new Intent(v.getContext(),MainActivity.class);
//startActivity(i);
//finish();
}
public void voice_list(View v)
{
if(recording_is_in_progress==false)
{
Intent i=new Intent(v.getContext(),SavedVoiceList.class);
startActivity(i);
finish();
}
}
public void about_us(View v)
{
//showtoast("status = "+recording_is_in_progress);
if(recording_is_in_progress==false)
{
Intent i=new Intent(v.getContext(),AboutUsActivity.class);
startActivity(i);
finish();
}
}
public void showtoast(String str)
{
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}
}//EOF Activit
Probably you have to request a android.permission.RECORD_AUDIO permission to be able to record it after Android 6 version.
please check the document
I have 2 problem in my audio recording application
1) I want a popup window which ask name of audio when i press stop button of audio recording activity, i have created this activity but it doesn't open popup and ask name, it stores audio with currentTimeMillis which i have specified in code, So how to get popup which ask to enter name of audio and it stores audio with particular entered name.
2) I have set timer of 20 seconds, mediaRecoder.setMaxDuration(20000); So what i want is after 20 seconds of time, i want that recording stop automatically and popup comes and ask for recorded audio name, same as requirement 1 but it should stop automatically after 20 seconds.
Below is my Activity Code.
public class Record_Audio extends Activity {
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
AUDIO_RECORDER_FILE_EXT_3GP };
Chronometer myChronometer;
Handler seekHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record_audio);
myChronometer = (Chronometer) findViewById(R.id.chronometer);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}
private void setButtonHandlers() {
((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button) findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
((Button) findViewById(R.id.allrecording)).setOnClickListener(btnClick);
}
private void enableButton(int id, boolean isEnable) {
((Button) findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart, !isRecording);
enableButton(R.id.btnFormat, !isRecording);
enableButton(R.id.btnStop, isRecording);
}
private void setFormatButtonCaption() {
((Button) findViewById(R.id.btnFormat))
.setText(getString(R.string.audio_format) + " ("
+ file_exts[currentFormat] + ")");
}
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[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();
}
myChronometer.setBase(SystemClock.elapsedRealtime());
myChronometer.start();
}
private void stopRecording() {
if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
myChronometer.stop();
}
}
private void displayFormatDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = { "MPEG 4", "3GPP" };
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
}).show();
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(Record_Audio.this, "Error: " + what + ", " + extra,
Toast.LENGTH_SHORT).show();
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Toast.makeText(Record_Audio.this,
"Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
.show();
}
};
private View.OnClickListener btnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart: {
Toast.makeText(Record_Audio.this, "Start Recording",
Toast.LENGTH_SHORT).show();
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop: {
Toast.makeText(Record_Audio.this, "Stop Recording",
Toast.LENGTH_SHORT).show();
enableButtons(false);
stopRecording();
break;
}
case R.id.btnFormat: {
displayFormatDialog();
break;
}
case R.id.allrecording: {
Intent intent = new Intent(Record_Audio.this, PlayAudio.class);
startActivity(intent);
break;
}
}
}
};
}
So mainly this below function is responsible for all the operation but i am not getting how to code.
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[currentFormat]);
}
Any help would be appreciated. Thanks in advance...
This is my main activity which is actually a tab activity. I am choosing list of song and i am trying to play radio in activity given below.
public class MainActivity extends TabActivity {
String[] actions = new String[] { "Tune-Up", "About Us", "Like-Us",
"Other", "Exit" };
Spinner country_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
TabHost tabHost = getTabHost();
TabSpec allcallspec = tabHost.newTabSpec("listner");
allcallspec.setIndicator("listener");
Intent allIntent = new Intent(this, Tab_Listner.class);
allcallspec.setContent(allIntent);
// Tab for recived call
TabSpec recivespec = tabHost.newTabSpec("Like");
// setting Title and Icon for the Tab
recivespec.setIndicator("Like");
Intent reciveIntent = new Intent(MainActivity.this, Tab_Like.class);
recivespec.setContent(reciveIntent);
TabSpec recivespec1 = tabHost.newTabSpec("Categery");
// setting Title and Icon for the Tab
recivespec1.setIndicator("CateGories");
Intent reciveIntent1 = new Intent(MainActivity.this,
Category_name.class);
recivespec1.setContent(reciveIntent1);
tabHost.addTab(recivespec);
tabHost.addTab(allcallspec); // Adding photos tab
// Adding songs tab
tabHost.addTab(recivespec1); // Adding songs tab
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuItem mainMenuSpinner = menu.findItem( R.id.menu_main_spinner);
// setupMainMenuSpinner( mainMenuSpinner );
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
getMenuInflater().inflate(R.menu.mainactivity, menu);
Log.i("Android Version is", "Belove Froyo Action Bar Not Displayed");
MenuItem statusSpinner = menu.findItem(R.id.menu_status_spinner);
setupStatusSpinner(statusSpinner);
}
return super.onCreateOptionsMenu(menu);
}
private void setupStatusSpinner(MenuItem item) {
View view = item.getActionView();
if (view instanceof Spinner) {
Spinner spinner = (Spinner) view;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, actions);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
switch (arg2) {
case 1:
Log.i("About US", "Go");
startActivity(new Intent(MainActivity.this,
About_Us.class));
break;
case 2:
String url = "https://www.facebook.com/musicbreeds";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
break;
case 3:
Log.i("Other", "Go");
startActivity(new Intent(MainActivity.this, Other.class));
break;
case 4:
Log.i("Exit", "unSuccess");
System.out.print("not.......................");
System.exit(0);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
TextView tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
}
}
Play_Radio activity, In this activity i play and pause songs. i want to have play/pause button at bottom in my MainActivity to stop and play current song.
public class Play_Radio extends Activity {
private ImageView playButton;
private TextView textStreamed, tv_radio_name, tv_radio_cat;
private boolean isPlaying;
private static StreamingMediaPlayer audioStreamer;
private AudioManager audioManager = null;
ImageView iv_like;
Dialog rankDialog;
RatingBar ratingBar, pre_rating;
float cus_rating;
AdView adView;
Dialog dialog;
public static String name, rating, like, radio_url, id, listner, image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.play_radio);
if (audioStreamer != null) {
try {
Log.i("Already ply", "Succss");
audioStreamer.stop();
} catch (Exception e) {
}
} else {
Log.i("First time", "Play");
}
initControls();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("On Pause is call", "Succcess");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", "" + currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
Log.i("Android Device above", "Home Enbled");
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
private void initControls() {
iv_like = (ImageView) findViewById(R.id.iv_activity_like);
iv_like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
Toast.makeText(getApplicationContext(),
"Thanks For like Our Station", Toast.LENGTH_LONG)
.show();
}
});
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
playButton = (ImageView) findViewById(R.id.imageView1);
playButton.setEnabled(false);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.i("Click sadg ", "success");
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v1.vibrate(40);
if (audioStreamer.getMediaPlayer().isPlaying()) {
Log.i("play ", "success");
audioStreamer.getMediaPlayer().pause();
playButton.setImageResource(R.drawable.play_radio_play);
} else {
Log.i("pause", "success");
audioStreamer.getMediaPlayer().start();
audioStreamer.startPlayProgressUpdater();
playButton.setImageResource(R.drawable.play_radio_pause);
}
isPlaying = !isPlaying;
}
});
// rating radio sation
ImageView rankBtn = (ImageView) findViewById(R.id.iv_activity_rating);
rankBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rankDialog = new Dialog(Play_Radio.this,
R.style.FullHeightDialog);
rankDialog.setContentView(R.layout.rating_bar);
rankDialog.setCancelable(true);
ratingBar = (RatingBar) rankDialog
.findViewById(R.id.dialog_ratingbar);
float userRankValue = 0;
// ratingBar.setRating(userRankValue);
ratingBar
.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromUser) {
// TODO Auto-generated method stub
cus_rating = rating;
}
});
Button updateButton = (Button) rankDialog
.findViewById(R.id.rank_dialog_button);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Play_Radio.this,
"Thanks For Rating Our Stations",
Toast.LENGTH_LONG).show();
rankDialog.dismiss();
}
});
// now that the dialog is set up, it's time to show it
rankDialog.show();
}
});
String urlstring2 = Tab_Listner.radio_url;
Toast.makeText(Play_Radio.this, "Please Wait...", Toast.LENGTH_LONG)
.show();
startStreamingAudio(urlstring2);
tv_radio_cat = (TextView) findViewById(R.id.tv_play_radio_cat);
tv_radio_name = (TextView) findViewById(R.id.tv_play_radio_name);
tv_radio_name.setText(Tab_Listner.name);
pre_rating = (RatingBar) findViewById(R.id.ratingBar1);
pre_rating.setRating(Float.parseFloat(Tab_Listner.rating));
}
private void startStreamingAudio(String urlstring) {
try {
dialog = new Dialog(Play_Radio.this,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.progress_layout);
dialog.setTitle("loading...");
dialog.show();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
if (audioStreamer != null) {
audioStreamer.interrupt();
}
audioStreamer = new StreamingMediaPlayer(this, textStreamed,
playButton, progressBar, dialog);
audioStreamer.startStreaming(urlstring, 5208, 216);
} catch (Exception e) {
Log.e(getClass().getName(), "Error starting to stream audio.", e);
}
}
public void onItemSelected(AdapterView parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
private Integer[] mImageIds = { R.drawable.calculator, R.drawable.calendar,
R.drawable.camera };
}
i have already add play/pause button in playradio activity and its work but i want to play pause button on mainactivity for start and stop play song which are already play run in to radio activity
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96 * 10 / 8;// assume
// 96kbps*10secs/8bits
// per byte
private TextView textStreamed;
private ImageView playButton;
private Dialog dialog;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context, TextView textStreamed,
ImageView playButton, ProgressBar progressBar, Dialog dialog) {
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
this.dialog = dialog;
}
public void startStreaming(final String mediaUrl, long mediaLengthInKb,
long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
// Dialog dialog=null;
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(),
"Unable to initialize the MediaPlayer for fileUrl="
+ mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(),
"Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),
"downloadingMedia.dat");
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead / 1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// mediaPlayer.release();
}
return false;
} else {
return true;
}
}
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum
// buffered data
if (totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error copying buffered conent.", e);
}
}
} else if (mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000) {
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
moveFile(downloadingMediaFile, bufferedFile);
Log.e(getClass().getName(),
"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),
"Buffered File length: " + bufferedFile.length() + "");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so
// update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.",
e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile) throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after
// transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File.
// Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),
"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(), "playingMedia"
+ (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on
// exit. If it's already deleted, then this won't mean anything. If
// you want to
// keep and track fully downloaded files for later use, write
// caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile, bufferedFile);
mediaPlayer.pause();
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
boolean atEndOfFile = mediaPlayer.getDuration()
- mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile) {
mediaPlayer.start();
}
oldBufferedFile.delete();
} catch (Exception e) {
Log.e(getClass().getName(),
"Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + "Kb"));
float loadProgress = ((float) totalKbRead / (float) mediaLengthInKb);
progressBar.setSecondaryProgress((int) (loadProgress * 100));
if (dialog != null)
dialog.dismiss();
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to
// the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed
.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float) mediaPlayer.getCurrentPosition() / 1000) / mediaLengthInSeconds);
progressBar.setProgress((int) (progress * 100));
if (dialog != null)
dialog.dismiss();
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
public void moveFile(File oldLocation, File newLocation) throws IOException {
if (oldLocation.exists()) {
BufferedInputStream reader = new BufferedInputStream(
new FileInputStream(oldLocation));
BufferedOutputStream writer = new BufferedOutputStream(
new FileOutputStream(newLocation, false));
try {
// byte[] buff = new byte[8192];
/* changing the size of the buffer */
byte[] buff = new byte[16384];
int numChars;
while ((numChars = reader.read(buff, 0, buff.length)) != -1) {
writer.write(buff, 0, numChars);
}
} catch (IOException ex) {
throw new IOException("IOException when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
} finally {
try {
if (reader != null) {
writer.close();
reader.close();
}
} catch (IOException ex) {
Log.e(getClass().getName(),
"Error closing files when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
} else {
throw new IOException(
"Old location does not exist when transferring "
+ oldLocation.getPath() + " to "
+ newLocation.getPath());
}
}
public void change_volume(float vol) {
Log.i("Media Player volume change", "Success" + vol);
mediaPlayer.setVolume(vol, vol);
}
public void stop() {
// TODO Auto-generated method stub
mediaPlayer.stop();
}
public void stoppreviousPlayer() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
// mediaPlayer.release();
}
}
}
you need a Service which is independent to the activity to play the song
public class SongService extends Service {
MediaPlayer mm;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mm = MediaPlayer.create(this, R.raw.mainmenu2);
mm.setLooping(true);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mm.stop();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
mm.start();
}
}
then add this whenever you want to play the song in the service.
startService(new Intent(this, SongService.class));
and to finish it add this:
stopService(new Intent(MainMenu.this,SongService.class));
So when you press the button start the service, and whenever you press the stop button stop it. this is how you can play songs through activities.
First you have to create a raw folder in res folder and paste the song you want to play there.
MainActivity,java======
protected void onCreate(){
MediaPlayer backgroundSong;
backgroundSong = MediaPlayer.create(MainActivity.this, R.raw.your_song_name);
backgroundSong.start();}
#Override
protected void stopSong() {
// TODO Auto-generated method stub
backgroundSong.release();
}
OtherActivity.java
protected void onPause(){
MainActivity ma = new MainActivity();
ma.stopSong();
}
What I'm trying to do:
I'm trying to write a program that reads audio from the android microphone (without recording) and captures some measure of how loud it is using a service.
For now I'm sending a pulse from my activity to my service to get a quick sound reading and checking the Logcat printout of the amplitude as my volumeter.
My problem:
The read method of AudioRecord returns 0.
What I've tried:
Recording full audio instead of using the NullOutputStream does not make a difference.
Some earlier versions randomly started working after some trivial changes like a logcat call was added and then stopped working later.
My thoughts:
I thought originally that maybe the microphone was being used by another application, but it still returns 0 even when this is the only notable service running.
my service:
import org.apache.commons.io.output.NullOutputStream;
public class RecordingService extends Service {
public static final int SAMPLE_RATE = 16000;
private AudioRecord mRecorder;
private File mRecording;
private short[] mBuffer;
public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
public double amplitude = 0.0;
public String TAG = "TAG";
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId){
initRecorder();
mRecorder.startRecording();
mRecording = getFile("raw");
startBufferedWrite(mRecording, intent);
mRecorder.stop();
mRecorder.release();
stopSelf();
return START_STICKY;
}
private void initRecorder() {
int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mBuffer = new short[bufferSize];
mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
}
private void startBufferedWrite(final File file, Intent intent) {
Log.i(TAG, "WRITING");
new Thread(new Runnable() {
#Override
public void run() {
DataOutputStream output = null;
Log.i(TAG, "running");
try {
output = new DataOutputStream(NULL_OUTPUT_STREAM);
Log.i(TAG, "outputset");
double sum = 0;
//problems!
Log.i(TAG, "mBufferlength= " + mBuffer.length);
int readSize = mRecorder.read(mBuffer, 0, mBuffer.length);
Log.i(TAG, "readSize1= " + readSize);
Log.i(TAG, mBuffer.toString());
//problems!
Log.i(TAG, "read");
for (int i = 0; i < readSize; i++) {
output.writeShort(mBuffer[i]);
sum += mBuffer[i] * mBuffer[i];
}
Log.i(TAG, "summed up");
if (readSize > 0) {
Log.i(TAG, "readSize2= "+readSize);
Log.i(TAG, "setting progress");
amplitude = sum / readSize;
Log.i(TAG, "amplitude= " + amplitude);
Log.i(TAG, "sqrt= " + Math.sqrt(amplitude));
}
else {
Log.i(TAG, "readsize <= 0");
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
if (output != null) {
try {
output.flush();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
try {
output.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
}
}
}
}
}).start();
}
private File getFile(final String suffix) {
Time time = new Time();
time.setToNow();
return new File(Environment.getExternalStorageDirectory(), time.format("%Y%m%d%H%M%S") + "." + suffix);
}
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
my activity:
public class RecordingActivity extends Activity {
private final String startRecordingLabel = "Start recording";
public String TAG = "TAG";
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setText(startRecordingLabel);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
Intent intent = new Intent(RecordingActivity.this, RecordingService.class);
Toast.makeText(RecordingActivity.this, "started", Toast.LENGTH_SHORT).show();
RecordingActivity.this.startService(intent);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
It's my first post, but I'm hoping that it's easy to follow. Thank you!
I am making an android application to record sound. I have been using class MediaRecorder for that.
The recording is done successfully when the recording is done for the first time on any device. But it doesn't work next time.
If I try the code on another machine, recording is done successfully. Is it so because MediaRecorder instance is not getting released by the app even if I am calling method release().
This is my code-
public class NewClass extends Activity {
private static String sFileName = null;
private static String sFileNameMSD = null;
private static String sPlayFile = null;
public MediaRecorder mRecorder = null;
private String mPn_id;
private String mDescription;
private String mTask_flag;
private String mPatient_name;
private String mPatient_id;
private String mIs_upload = "N";
private Context mContext;
Button btnStart;
Button btnStop;
private int mReuqestcode;
NewClass myActivity;
SeekBar seekBar;
int totalTime;
private final Handler handler = new Handler();
private final String FILE_EXTENTION_AMR = ".amr";
private final String FILE_EXTENTION_MSD = ".msd";
protected boolean recodeFlag = false;;
private static final String TAG = GridAllActivity.class.getName();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.transcriptionrecord_activity);
mContext = this;
myActivity = this;
Main.setTitle(myActivity, mContext);
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
mContext));
TextView txtTitle = (TextView) findViewById(R.id.txt_Title1);
txtTitle.setText("Transcription");
TextView txtOption = (TextView) findViewById(R.id.txtOptionName);
TextView txtPatientName = (TextView) findViewById(R.id.txtPatientName);
setProperty();
txtOption.setText("" + mDescription);
txtPatientName.setText("" + mPatient_name);
}
private void onRecord(boolean start) throws SettingNotFoundException {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() throws SettingNotFoundException {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mRecorder.setOutputFile(sFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
recodeFlag=true;
Log.e("1", "prepare() failed");
e.printStackTrace();
}
}
private void stopRecording() throws SettingNotFoundException {
mRecorder.stop();
mRecorder.release();
Log.d("1", "mRecorder released");
mRecorder = null;
System.gc();
}
public void setRecordPath() throws IOException {
sFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
sFileName += Global.creteFolderPath("IMSEMR" + mTask_flag + "_"
+ mPn_id + FILE_EXTENTION_AMR);
sFileNameMSD = "IMSEMR" + mTask_flag + "_" + mPn_id
+ FILE_EXTENTION_MSD;
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Global.alertbox("", "SD Card is not mounted.", mContext);
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
File directory = new File(sFileName).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
directory.mkdirs();
throw new IOException("Path to file could not be created.");
}
}
public void setRecodingLayout() {
btnStop.setEnabled(false);
try {
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean mStartRecording = true;
try {
btnStop.setEnabled(true);
btnStart.setEnabled(false);
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
}
});
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
boolean mStartRecording = false;
try {
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
} catch (SQLiteException e) {
// TODO: handle exception
} catch (Exception e) {
// TODO: handle exception
}
}
});
} catch (NullPointerException e) {
}
}
public void setProperty() {
Bundle bundel = getIntent().getExtras();
mReuqestcode = (Integer) bundel.get("REQUEST_CODE");
// property for Record
if (mReuqestcode == 1) {
mPn_id = (String) bundel.get("PN_ID");
mDescription = (String) bundel.get("DESCRIPTION");
mTask_flag = (String) bundel.get("TASK_FLAG");
mPatient_id = (String) bundel.get("PATIENT_ID");
mPatient_name = (String) bundel.get("PATIENT_NAME");
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setEnabled(false);
setRecodingLayout();
try {
setRecordPath();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You need to create a new instance of media recorder each time you want to record (making sure to release the previous one).
Update --
Sorry, you only need to create a new instance if you call release on the object. Otherwise you can just call reset,
read this: http://developer.android.com/reference/android/media/MediaRecorder.html
Example:
Lets say you have an activity with 2 buttons, a record button and a play button
public class MyRecordDemo extends Activity {
private static final String PATH_NAME = "/sdcard/myfile.3gp"; //probably shouldn't hardcode this
private Button mRecordButton, mStopButton;
private MediaRecorder mRecorder = null;
private boolean mIsRecording = false;
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.recorder_demo);
mRecordButton = (Button) findViewById(R.id.record_btn);
mStopButton = (Button) findViewById(R.id.stop_btn);
mStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
}
});
mRecordButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(PATH_NAME);
mRecorder.prepare();
mRecorder.start()
}
});
}
}