I writting a music application play music with url get from website. In code of me, i using method prepared() and app work. But method prepared() block UI this makes me uncomfortable... I want using method prepareAsync()... But i don't know use it :(. I'm newbie with Android Programing. Please edit my code...!
I speak English bad. Sorry for the inconvenience
Code here :
Function playSong()
private void playSong(String urlData) {
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnPlay.setOnClickListener(this);
seekBar.setMax(99);
seekBar.setOnTouchListener(this);
mPlay = new MediaPlayer();
mPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlay.setOnBufferingUpdateListener(this);
mPlay.setOnCompletionListener(this);
try {
mPlay.setDataSource(urlData);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
if (mPlay != null) {
mPlay.start();
btnPlay.setImageResource(R.drawable.pause_icon);
} else {
mPlay.pause();
btnPlay.setImageResource(R.drawable.play);
}
mPlay.start();
primaryUpdateSeekBar();
}
Function onClick use play
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnPlay) {
try {
mPlay.prepare();
} catch (Exception e) {
e.printStackTrace();
}
LenghData = mPlay.getDuration();
if (!mPlay.isPlaying()) {
mPlay.start();
btnPlay.setImageResource(R.drawable.pause_icon);
} else {
mPlay.pause();
btnPlay.setImageResource(R.drawable.play);
}
primaryUpdateSeekBar();
}
}
Functions of Seekbar
private void primaryUpdateSeekBar() {
seekBar.setProgress((int) (((float) mPlay.getCurrentPosition() / LenghData) * 100));
if (mPlay.isPlaying()) {
Runnable notification = new Runnable() {
#Override
public void run() {
long totalDuration = mPlay.getDuration();
long currentDuration = mPlay.getCurrentPosition();
tvTotalTime.setText(Utils.getTimeString(totalDuration));
tvCurrentTime.setText(Utils.getTimeString(currentDuration));
primaryUpdateSeekBar();
}
};
handler.postDelayed(notification, 1000);
}
}
#Override
public void onBackPressed() {
if (mPlay.isPlaying()) {
mPlay.stop();
}
super.onBackPressed();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
btnPlay.setImageResource(R.drawable.play);
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
tvTotalTime.setText("00:00");
tvCurrentTime.setText("");
try {
playSong(ifChangeCheck);
mPlay.prepareAsync();
mPlay.setOnPreparedListener(this);
mPlay.setLooping(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
#Override
public boolean onTouch(View view, MotionEvent event) {
if (view.getId() == R.id.seekBar) {
SeekBar seekbar = (SeekBar) view;
int playPositioninMiliseconds = (LenghData / 100)
* seekbar.getProgress();
mPlay.seekTo(playPositioninMiliseconds);
}
return false;
}
Final
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.rad32Kb:
String aftercheck32 = "";
int checkLinkIsPlay32 = urlDataSource.lastIndexOf("/") - 3;
String subString32 = urlDataSource.substring(checkLinkIsPlay32);
if (subString32.contains("128")) {
aftercheck32 = urlDataSource.replace("/128/", "/32/").replace(
".mp3", ".m4a");
} else if (subString32.contains("320")) {
aftercheck32 = urlDataSource.replace("/320/", "/32/").replace(
".mp3", ".m4a");
} else if (subString32.contains("m4a")) {
aftercheck32 = urlDataSource.replace("/m4a/", "/32/");
}
ifChangeCheck = aftercheck32;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad128Kb:
try {
if (mPlay != null) {
ifChangeCheck = urlDataSource;
mPlay.stop();
mPlay.reset();
}
playSong(urlDataSource);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad320Kb:
String aftercheck320 = "";
int checkLinkIsPlay320 = urlDataSource.lastIndexOf("/") - 3;
String subLink320 = urlDataSource.substring(checkLinkIsPlay320);
if (subLink320.contains("/32")) {
aftercheck320 = urlDataSource.replace("/32/", "/320/").replace(
".m4a", ".mp3");
} else if (subLink320.contains("128")) {
aftercheck320 = urlDataSource.replace("/128/", "/320/");
} else if (subLink320.contains("m4a")) {
aftercheck320 = urlDataSource.replace("/m4a/", "/320/")
.replace(".m4a", ".mp3");
}
ifChangeCheck = aftercheck320;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case R.id.rad500:
String aftercheck500 = "";
int checkLinkIsPlay500 = urlDataSource.lastIndexOf("/") - 3;
String subLink500 = urlDataSource.substring(checkLinkIsPlay500);
if (subLink500.contains("/32")) {
aftercheck500 = urlDataSource.replace("/32/", "/m4a/");
} else if (subLink500.contains("128")) {
aftercheck500 = urlDataSource.replace("/128/", "/m4a/")
.replace(".mp3", ".m4a");
} else if (subLink500.contains("320")) {
aftercheck500 = urlDataSource.replace("/320/", "/m4a/")
.replace(".mp3", ".m4a");
}
ifChangeCheck = aftercheck500;
try {
if (mPlay != null) {
mPlay.stop();
mPlay.reset();
}
playSong(ifChangeCheck);
mPlay.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
Above is all code in class PlayMusicActivity of me... And thanks for helping me
Call the prepareAsync() method from the playsong method, as it will starting buffering the audio immediately. When enough audio has buffered the onPrepared method will be called and audio will play
private void playSong(String urlData) {
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnPlay.setOnClickListener(this);
seekBar.setMax(99);
seekBar.setOnTouchListener(this);
mPlay = new MediaPlayer();
mPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlay.setOnBufferingUpdateListener(this);
mPlay.setOnCompletionListener(this);
try {
mPlay.setDataSource(urlData);
mPlay.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
the issue is, I have checked whether media player is null or not, if not I have applied release() method but still when I select another song to play, it plays new song but it doesn't stop the previous one. While playing next or previous on click also works fine. so why it is not detecting that mediaplayer is playing.
here is java code.
public class Musicplay extends AppCompatActivity implements View.OnClickListener {
Button play,next,previous;
TextView songmar;
SeekBar seekBar;
MediaPlayer mediaPlayer;
int position,idr;
Handler handler=new Handler();
Handler vindler=new Handler();
Uri uri;
int max;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playdisplay);
Intent i=getIntent();
position=i.getIntExtra("position",0);
play=findViewById(R.id.pause);
next=findViewById(R.id.next);
previous=findViewById(R.id.previous);
songmar=findViewById(R.id.songnamemar);
songmar.setSelected(true);
songmar.setText(Musiclist.songname.get(position));
seekBar=findViewById(R.id.seekBar);
if(mediaPlayer==null)
{
Log.d("null","null");
}
else {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
else {
mediaPlayer.release();
}
}
uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
mediaPlayer=MediaPlayer.create(Musicplay.this,uri);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
max=mediaPlayer.getDuration();
play.setBackgroundResource(R.drawable.ic_pause);
Thread thread=new Thread(){
#Override
public void run() {
super.run();
int currentposition=0;
while (currentposition<max)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentposition=mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentposition);
}
}
};
thread.start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
next.setOnClickListener(Musicplay.this);
play.setOnClickListener(Musicplay.this);
previous.setOnClickListener(Musicplay.this);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
}
else
{
position=0;
}
uri = Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mp.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setMax(mp.getDuration());
max=mp.getDuration();
Log.d("seekvalue",String.valueOf(max));
}
});
}
#Override
public void onClick(View v) {
idr=v.getId();
Thread thread2=new Thread(){
#Override
public void run() {
super.run();
handler.post(new Runnable() {
#Override
public void run() {
switch (idr){
case R.id.pause:
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
play.setBackgroundResource(R.drawable.ic_play);
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
break;
case R.id.next:
mediaPlayer.stop();
mediaPlayer.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=0;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
case R.id.previous:
mediaPlayer.stop();
mediaPlayer.reset();
if(position>0){
position=position-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=Musiclist.songname.size()-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
}
}
});
}
};
thread2.start();
}
}
so do suggest reason why this error is taking place, and it is playing two or multiple song simultaneously.
all you have to do is, just declare mediaplayer variable public static and when you start activity to play song just check for media player is null or not and then release it
The Path where the file is located "/storage/sdcard/MediaRecorderSample/Recordingg2"
The errors i am getting
E/MediaPlayer: stop called in state 1,E/MediaPlayer: error (-38, 0),D/MediaPlayer: Couldn't open file on client side, trying server side
Here is my code
public class Player extends AppCompatActivity implements View.OnClickListener {
static MediaPlayer mp;
SeekBar sb;
ArrayList mysongs;
int pos;
Uri u;
Thread th;
String filepath;
File file;
Button btprev,btfb,btplay,btff,btnext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
mp = new MediaPlayer();
filepath = android.os.Environment.getExternalStorageDirectory().getPath();
file = new File(filepath,"MediaRecorderSample");
btplay=(Button) findViewById(R.id.btplay);
btff=(Button) findViewById(R.id.btff);
btnext=(Button) findViewById(R.id.btnxt);
btprev=(Button) findViewById(R.id.btprev);
btfb=(Button) findViewById(R.id.btfb);
btplay.setOnClickListener(this);
btff.setOnClickListener(this);
btnext.setOnClickListener(this);
btfb.setOnClickListener(this);
btprev.setOnClickListener(this);
sb= (SeekBar) findViewById(R.id.seekBar);
th = new Thread(){
#Override
public void run() {
int totalduration= mp.getDuration();
int currentposition=0;
sb.setMax(totalduration);
while(currentposition < totalduration)
{
try {
sleep(500);
currentposition = mp.getCurrentPosition();
sb.setProgress(currentposition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//super.run();
}
};
// if(mp!=null)
// {
// mp.stop();
// mp.reset();
// mp.release();
// }
Intent i = getIntent();
Bundle b= i.getExtras();
pos = b.getInt("pos");
mysongs= b.getStringArrayList("mysongs");
Log.d("Mystring", String.valueOf(mysongs));
Log.d("path1",file.getAbsolutePath()+ "/" + mysongs.get(pos));
u = Uri.parse(file.getAbsolutePath()+ "/" + mysongs.get(pos)+".wav");
//mp.create(getApplicationContext(),u);
try {
if (mp != null) {
mp.stop();
}
mp.setDataSource(getApplicationContext(),u);
//mp.prepare();
mp.start();
th.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// mp = MediaPlayer.create(getApplicationContext(),u);
// try {
// mp.setDataSource(getApplicationContext(),u);
// mp.start();
// } catch (IOException e) {
// e.printStackTrace();
// }
//mp.start();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.btplay:
if(mp.isPlaying())
{
btplay.setText(">");
mp.pause();
}
else {
btplay.setText("||");
mp.start();
}
break;
case R.id.btff:
mp.seekTo(mp.getCurrentPosition()+ 5000);
break;
case R.id.btfb:
mp.seekTo(mp.getCurrentPosition()-5000);
break;
case R.id.btnxt:
mp.stop();
mp.reset();
mp.release();
pos =(pos+1)%mysongs.size();
u = Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.btprev:
mp.stop();
mp.reset();
mp.release();
pos =(pos-1<0)? mysongs.size()-1: pos-1;
u= Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
`
I have a problem with changing URL of live stream in the MediaPlayer instance. When I tap on a ListView item for a first time, live streaming is started and video is displayed, but if I click on another object in the ListView, stream is not changed, the same stream continues to play which was executed at first time.
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
ArrayList<Channel> channels;
Channel clickedChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
controller = new VideoControllerView(this);
player = new MediaPlayer();
channels = new ArrayList<Channel>();
CreateChannels();
ListView lvMain = (ListView) findViewById(R.id.lvMain);
CustomAdapter adapter = new CustomAdapter(this, channels);
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
clickedChannel = channels.get(position);
}
}
}
PlayStream(clickedChannel.Streams[0].URL);
}
});
}
public void PlayStream(String URL) {
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// missed code
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
}
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
}
Solved my problem by recreating player instance every time
public void PlayStream(String URL) {
releaseMP();
try {
player = new MediaPlayer();
player.setDisplay(videoHolder);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void releaseMP() {
if (player != null) {
try {
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMP();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.
Hi there I have built a soundboard for a character of mine called Aussie Bloke - the soundboard contains 30 buttons and 30 mediaplayers. I originally used one mediaplayer for all buttons but eventually the sounds would stop playing after about 20 random presses. So I decided on using seperate mediaplayer objects for each sound as used in the original soundboard template I used. This worked fine you could press buttons all day and get sounds working properly ..but the problem I have is that when the activity is sent to the background and brought back again even after a few seconds the app crashes when you press a button..I tried creating an onResume method to prepare all the players but this just made the app crash right from the start..sorry I am very new to coding and app building so there may be an obvious solution I have overlooked or been completely unaware of.
package com.zammacat.aussiebloke1;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AUSSIEBLOKE1 extends Activity {
private static final String BASE64_PUBLIC_KEY = "key here";
MediaPlayer beer1;
MediaPlayer beer2;
MediaPlayer beer3;
MediaPlayer beauty;
MediaPlayer boner;
MediaPlayer death;
MediaPlayer dingo;
MediaPlayer dogupya;
MediaPlayer donotpress;
MediaPlayer enough;
MediaPlayer heaven;
MediaPlayer help;
MediaPlayer hungry;
MediaPlayer kebab;
MediaPlayer kids;
MediaPlayer knees;
MediaPlayer later;
MediaPlayer meatpie;
MediaPlayer medal;
MediaPlayer oath;
MediaPlayer poem;
MediaPlayer politics;
MediaPlayer pub;
MediaPlayer sex;
MediaPlayer sport;
MediaPlayer strewth;
MediaPlayer tango;
MediaPlayer v8;
MediaPlayer what;
MediaPlayer yoursister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aussiebloke1);
beer1 = MediaPlayer.create(this, R.raw.beer1);
beer2 = MediaPlayer.create(this, R.raw.beer2);
beer3 = MediaPlayer.create(this, R.raw.beer3);
beauty = MediaPlayer.create(this, R.raw.beauty);
boner = MediaPlayer.create(this, R.raw.boner);
death = MediaPlayer.create(this, R.raw.death);
dingo = MediaPlayer.create(this, R.raw.dingo);
dogupya = MediaPlayer.create(this, R.raw.dogupya);
donotpress = MediaPlayer.create(this, R.raw.donotpress);
enough = MediaPlayer.create(this, R.raw.enough);
heaven = MediaPlayer.create(this, R.raw.heaven);
help = MediaPlayer.create(this, R.raw.help);
hungry = MediaPlayer.create(this, R.raw.hungry);
kebab = MediaPlayer.create(this, R.raw.kebab);
kids = MediaPlayer.create(this, R.raw.kids);
knees = MediaPlayer.create(this, R.raw.knees);
later = MediaPlayer.create(this, R.raw.later);
meatpie = MediaPlayer.create(this, R.raw.meatpie);
medal = MediaPlayer.create(this, R.raw.medal);
oath = MediaPlayer.create(this, R.raw.oath);
poem = MediaPlayer.create(this, R.raw.poem);
politics = MediaPlayer.create(this, R.raw.politics);
pub = MediaPlayer.create(this, R.raw.pub);
sex = MediaPlayer.create(this, R.raw.sex);
sport = MediaPlayer.create(this, R.raw.sport);
strewth = MediaPlayer.create(this, R.raw.strewth);
tango = MediaPlayer.create(this, R.raw.tango);
v8 = MediaPlayer.create(this, R.raw.v8);
what = MediaPlayer.create(this, R.raw.what);
yoursister = MediaPlayer.create(this, R.raw.yoursister);
Button b01 = (Button) findViewById(R.id.beer1);
b01.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
beer1.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
beer1.start();
}
});
Button b02 = (Button) findViewById(R.id.beer2);
b02.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
beer2.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
beer2.start();
}
});
Button b03 = (Button) findViewById(R.id.beer3);
b03.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
beer3.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
beer3.start();
}
});
Button b04 = (Button) findViewById(R.id.beauty);
b04.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
beauty.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
beauty.start();
}
});
Button b05 = (Button) findViewById(R.id.boner);
b05.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
boner.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
boner.start();
}
});
Button b06 = (Button) findViewById(R.id.death);
b06.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
death.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
death.start();
}
});
Button b07 = (Button) findViewById(R.id.dingo);
b07.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
dingo.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dingo.start();
}
});
Button b08 = (Button) findViewById(R.id.dogupya);
b08.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
dogupya.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dogupya.start();
}
});
Button b09 = (Button) findViewById(R.id.donotpress);
b09.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
donotpress.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
donotpress.start();
}
});
Button b10 = (Button) findViewById(R.id.enough);
b10.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
enough.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
enough.start();
}
});
Button b11 = (Button) findViewById(R.id.heaven);
b11.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
heaven.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
heaven.start();
}
});
Button b12 = (Button) findViewById(R.id.help);
b12.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
help.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
help.start();
}
});
Button b13 = (Button) findViewById(R.id.hungry);
b13.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
hungry.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hungry.start();
}
});
Button b14 = (Button) findViewById(R.id.kebab);
b14.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
kebab.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
kebab.start();
}
});
Button b15 = (Button) findViewById(R.id.kids);
b15.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
kids.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
kids.start();
}
});
Button b16 = (Button) findViewById(R.id.knees);
b16.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
knees.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
knees.start();
}
});
Button b17 = (Button) findViewById(R.id.later);
b17.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
later.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
later.start();
}
});
Button b18 = (Button) findViewById(R.id.meatpie);
b18.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
meatpie.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
meatpie.start();
}
});
Button b19 = (Button) findViewById(R.id.medal);
b19.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
medal.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
medal.start();
}
});
Button b20 = (Button) findViewById(R.id.oath);
b20.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
oath.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
oath.start();
}
});
Button b21 = (Button) findViewById(R.id.poem);
b21.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
poem.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
poem.start();
}
});
Button b22 = (Button) findViewById(R.id.politics);
b22.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
politics.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
politics.start();
}
});
Button b23 = (Button) findViewById(R.id.pub);
b23.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
pub.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
pub.start();
}
});
Button b24 = (Button) findViewById(R.id.sex);
b24.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
sex.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sex.start();
}
});
Button b25 = (Button) findViewById(R.id.sport);
b25.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
sport.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sport.start();
}
});
Button b26 = (Button) findViewById(R.id.strewth);
b26.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
strewth.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
strewth.start();
}
});
Button b27 = (Button) findViewById(R.id.tango);
b27.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
tango.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
tango.start();
}
});
Button b28 = (Button) findViewById(R.id.v8);
b28.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
v8.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
v8.start();
}
});
Button b29 = (Button) findViewById(R.id.what);
b29.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
what.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
what.start();
}
});
Button b30 = (Button) findViewById(R.id.yoursister);
b30.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try {
yoursister.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
yoursister.start();
}
});
}
protected void onStop() {
super.onStop();
beer1.release();
beer2.release();
beer3.release();
beauty.release();
boner.release();
death.release();
dingo.release();
dogupya.release();
donotpress.release();
enough.release();
heaven.release();
help.release();
hungry.release();
kebab.release();
kids.release();
knees.release();
later.release();
meatpie.release();
medal.release();
oath.release();
poem.release();
politics.release();
pub.release();
sex.release();
sport.release();
strewth.release();
tango.release();
v8.release();
what.release();
yoursister.release();
}
}
You need to implement onResume() method in your activity and recreate there your mediaplayer objects:
public void onResume() {
super.onResume();
// ...
beer1 = MediaPlayer.create(this, R.raw.beer1);
beer2 = MediaPlayer.create(this, R.raw.beer2);
beer3 = MediaPlayer.create(this, R.raw.beer3);
// ...
}
You can read more about Activity lifecycle here: http://developer.android.com/training/basics/activity-lifecycle/index.html