For an assignment I am trying to play songs from an array using media player. The first song in the array plays fine, but the next, and last track buttons are where my issue is. Could anyone suggest a way of playing the next/last song from my music array?
None relevant code not included.
// Arrays of sound files
private int[] audioFileArrayChill = {R.raw.vanilla_summer, R.raw.lifeline, R.raw.remember_the_mountain_bed};`
// Listen for the end of the track
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
for (int x = 1; x <= audioArray.length; x++) {
currentIndex++;
// Play next song in array
mp.selectTrack(audioArray[x]);
mp.start();
}
}
});
// Assigning onClickListener to last track button
lastTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.reset();
mediaPlayer.selectTrack(audioArray[currentIndex - 1]);
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("Error", "ERROR");
}
}
});
// Assigning onClickListener to next track button
nextTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.reset();
mediaPlayer.selectTrack(audioArray[currentIndex + 1]);
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("Error", "ERROR");
}
}
});
use below code for next button click
nextTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
mp.setDataSource(audioArray[currentIndex + 1]);
mp.prepare();
mp.start();
}
Related
Hi I have the following code that simply displays an RTSP on a TextureView to then make a screenShot of the stream and save it as an image,
playButton.setOnClickListener(this);
playButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(String.valueOf(Uri.parse("rtsp://........./")));
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
playButton.setVisibility(View.INVISIBLE);
btnCapture.setVisibility(View.VISIBLE);
recordVideo.setVisibility(View.VISIBLE);
}
});
}
});
recordVideo.setOnClickListener(this);
recordVideo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
how can I record a portion of this video and save it as mp4? I made the start and stop buttons for recording the video Can I save the video between the start and stop?
I'm creating a recorder app with chronometer counter, the chronometer is working fine with start record, stop record and stop play.
My problem is only with start play, when pressing start play button, the chronometer start from 0 but I couldn't stop the chronometer when the audio file stops.
This is the start play code, please help. Any help I greatly appreciated
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
stopRecord.setEnabled(false);
startRecord.setEnabled(false);
stopAudio.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
if (!running) {
myChronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
myChronometer.start();
running = true;
// myChronometer.stop();
}
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
Sir, this the code of stop audio
stopAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (running) {
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
pauseOffset = SystemClock.elapsedRealtime() - myChronometer.getBase();
running = false;
}
stopRecord.setEnabled(false);
startRecord.setEnabled(true);
stopAudio.setEnabled(false);
playAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
// MediaRecorderReady();
//resetmymyChronometer
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
}
}
});
this is the code of stop record
stopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (running) {
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
pauseOffset = SystemClock.elapsedRealtime() - myChronometer.getBase();
running = false;
}
mediaRecorder.stop();
stopRecord.setEnabled(false);
playAudio.setEnabled(true);
startRecord.setEnabled(true);
stopAudio.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
MediaRecorderReady method
public void MediaRecorderReady(){
//myChronometer start
if (!running) {
myChronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
myChronometer.start();
running = true;
//***********************
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
}
startRecord Listener
startRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
startRecord.setEnabled(true);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startRecord.setEnabled(false);
stopRecord.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
You can use OnCompletionListener, for example:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// your code to stop record
}
});
for more information :
https://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener
The line
myChronometer.stop();
is never called.
In your playAudio's onClick() method, you should set
running = true
i have a RecyclerView that displays a list of songs and i have successfully implemented on click listener with it and verified it with logs. Now i want to play the song upon click event. When i first click on a item the songs starts to play but if i then tap on any other item the app simply crashes
Here is my RecyclerViewClickListener
SongAdapter songAdapter = new SongAdapter(getContext(), songsList, new RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(getContext(), "You clicked on Ssong "+songsList.get(position).getSongName(), Toast.LENGTH_SHORT)
.show();
songPath = songsList.get(position).getUrl();
Log.v("Song Path", songPath);
if(mp.isPlaying())
releaseMediaResources();
playSong();
}
});
recyclerView.setAdapter(songAdapter);
Here is my playSong method
private void playSong () {
if(!songPath.equals("")) {
try {
mp.setDataSource(songPath);
} catch (Exception e) {
Log.e("Home Fragment", "Error setting song Url", e);
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release();
}
});
}
}
And here is my releaseMediaResources
private void releaseMediaResources() {
mp.stop();
mp.reset();
mp.release();
}
These are the errors
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.ashutosh.prototype4.HomeFragment.playSong(HomeFragment.java:159)
at com.ashutosh.prototype4.HomeFragment.releaseMediaResources(HomeFragment.java:192)
at com.ashutosh.prototype4.HomeFragment.access$100(HomeFragment.java:31)
at com.ashutosh.prototype4.HomeFragment$2.onClick(HomeFragment.java:94)
at com.ashutosh.prototype4.SongAdapter$1.onClick(SongAdapter.java:50)
According to me the main problem lies in setting up the media player because when i display only toast messages there's no issues at all but as soon as i implement media player to on click method the crash occurs
I will create every time the new MediaPlayer, but of course try to check, if there is not already existing instance for instance:
private MediaPlayer mediaPlayer;
private void playSong(String filePath) {
if (mediaPlayer != null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(filePath));
mediaPlayer.setVolume(DEFAULT_VOLUME_MUSIC, DEFAULT_VOLUME_MUSIC);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
});
}
Button btnPlayPause, btnNext, btnPrevious;
Bundle b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
b = currSong.getExtras();
btnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btnPlayPause.setText("Play");
} else {
mediaPlayer.start();
btnPlayPause.setText("Stop");
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlayPause.setText("Play");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
int songIndex = (int) b.get("songIndex");
#Override
public void onClick(View v) {
if (songIndex < songList.size() - 1) {
songIndex = songIndex + 1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
songIndex=0;
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (songIndex > 0){
songIndex = songIndex-1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else {
songIndex = songList.size() - 1;
}
}
});
}
}
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1] so there is always one song not playing.
How can i solve this or is there an easier way too go to the next song?
Thanks,
-Vince
EDIT;
Problem 2; when i choose a song, lets say with position 37, and i click on previous it goes to 36, but if i then click on next it goes to 38, so it skips the song i played first.
EDIT 2 ;
Ok problems still persists, but i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25. How can i solve this? Thanks in advance, - vince
Ok, you have several problems here:
i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25
In PlayNext's first line, you reassign songIndex to the original songIndex passed to the activity. PlayPrevious uses another songIndex that I can't see where is defined. If you had followed Android guidelines to always prefix with an "m" the class properties vs local variables, you'd easily have realised it.
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1]
The edge cases where user plays the next after the last song, or the previous after the first are incorrectly coded. In those cases you correctly update songIndex, but do not call play.
Besides the problems, what you should do is to rework your code a little using functions, to avoid repeating functionality. That is always prone to these kind of errors. I'd suggest something like this:
int mCurrentIndex; // always prefix class properties with an "m"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
Button btnPlayPause = (Button) findViewById(R.id.btnPlayPause),
btnNext = (Button) findViewById(R.id.btnNext),
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
Bundle b = currSong.getExtras();
// load initial index only once
mCurrentIndex = (int) b.get("songIndex");
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = mCurrentIndex > 0 ? mCurrentIndex - 1 : mSongList.size() - 1;
playSongNumber(mCurrentIndex);
}
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex++;
mCurrentIndex %= mSongList.size();
playSongNumber(mCurrentIndex);
}
}
}
private void playSongNumber(int index) {
try {
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.setDataSource(mSongList.get(index).getData());
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
slightly cleaner, isn't it?
I try to replay a sound when I click on a button. But I get the Error (-19, 0) (what ever this means^^)
My code:
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
What is my mistake?
I was getting the same problem, I solved it by adding the following code:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
You need to release the previous media player before starting the new one.
Declare MediaPlayer as a instance variable and then:
mp = null;
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
Or in your case, since you always play the same sound you don't need to release the player and create a new one, simply reuse the old one.
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.prepare(); // Blocking method. Consider to use prepareAsync
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
mp.start();
}
});
I sloved this problem by this code:
public static void playSound() {
mMediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd("type.mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.release();
}
});
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i hope to help you.