How to get to the beginning of activity with MediaPlayer - java

Need to pick another random track after stopping the previous one by clicking "stop" button
I'm playing a random track by clicking "play" button, stop it by clicking "stop" and then i need to randomize again, in other words, to pick another track.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button play36 = (Button) findViewById(R.id.threesix);
Button stop = (Button) findViewById(R.id.stop);
String[] listOfFiles = new String[0];
try {
listOfFiles = getAssets().list("");
final List<String> musicOnlyList = new ArrayList<>();
for (int i = 0; i < listOfFiles.length; i++) {
if (getExtension(listOfFiles[i]).equals("mp3"))
musicOnlyList.add(listOfFiles[i]);
}
final MediaPlayer mediaPlayer = new MediaPlayer();
play36.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemIndex = new Random().nextInt(musicOnlyList.size());
String file = musicOnlyList.get(itemIndex);
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd(file);
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.reset();
}
});
} catch (IOException e) {
e.printStackTrace();
}
In this case i get the same track everytime i start and stop player, but need to randomize everytime by clicking "play" button

You need to pick a new random number inside the listener of play36:
Button play36 = (Button)findViewById(R.id.threesix);
Button stop = (Button)findViewById(R.id.stop);
String[] listOfFiles = new String[0];
try {
listOfFiles = getAssets().list("");
final List<String> musicOnlyList = new ArrayList<>();
for(int i = 0; i < listOfFiles.length; i++){
if (getExtension(listOfFiles[i]).equals("mp3"))
musicOnlyList.add(listOfFiles[i]);
}
final MediaPlayer mediaPlayer = new MediaPlayer();
play36.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemIndex = new Random().nextInt(musicOnlyList.size());
String file = musicOnlyList.get(itemIndex);
AssetFileDescriptor afd = null;
try {
afd = getAssets().openFd(file);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}

Related

register a sound to a button click

I want to be able to press the button and have the sound play on every press. as of right now it only plays after it finishes playing the first time, not on every press.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer boost = MediaPlayer.create(this, R.raw.boost);
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!boost.isPlaying())
{
boost = new MediaPlayer();
}
try {
AssetFileDescriptor afd = res.openRawResource(R.raw.boost);
boost.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
boost.prepare();
boost.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
if (!boost.isPlaying())
{
boost= new MediaPlayer();
}
try {
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.boost);
boost.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
boost.prepare();
boost.start();
} catch (Exception e) {
e.printStackTrace();
}
}

not able to play next song on clicking a button

I am new to android development.I created an audio player app for playing songs from SD card,its working fine and song is being played but when I click next button, song doesn't change and same track keeps playing.Button is clickable but song doesn't change on clicking it.How do I fix it ? any kind of help is appreciated,thanks.
public class PlayListActivity extends Activity {
private String[] mAudioPath;
private MediaPlayer mMediaPlayer;
private String[] mMusicList;
int currentPosition = 0;
private List<String> songs = new ArrayList<>();
MediaMetadataRetriever metaRetriver;
byte[] art;
ImageView album_art;
TextView album;
TextView artist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_list);
mMediaPlayer = new MediaPlayer();
ListView mListView = (ListView) findViewById(R.id.list);
mMusicList = getAudioList();
ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, mMusicList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
try {
playSong(mAudioPath[arg2]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}
private void playSong(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
setContentView(R.layout.activity_android_building_music_player);
Log.d("ringtone", "playSong :: " + path);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
acv(path);
abc();
cde();
}
public void acv(String path) {
getInit();
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(path);
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
album_art.setImageBitmap(songImage);
album.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
artist.setText(metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
} catch (Exception e) {
album_art.setBackgroundColor(Color.GRAY);
album.setText("Unknown Album");
artist.setText("Unknown Artist");
}
}
public void getInit() {
album_art = (ImageView) findViewById(R.id.coverart1);
album = (TextView) findViewById(R.id.Album);
artist = (TextView) findViewById(R.id.artist_name);
}
public void abc() {
ImageButton btnPlay1 = (ImageButton) findViewById(R.id.btnPlay1);
btnPlay1.setBackgroundColor(Color.TRANSPARENT);
btnPlay1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
}
public void cde() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext); //this is the button for playing next song.
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
currentPosition=currentPosition+1;
playSong(path + songs.get(currentPosition));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
Try this code :
public void next() {
ImageButton btnNext = (ImageButton) findViewById(R.id.btnNext);
btnNext.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
temp = temp + 1;
try {
playSong(mAudioPath[temp]);
} catch (Exception er) {
er.printStackTrace();
}
}
}
);
}
Dont forget to declare next() method in playsong()

AssetFileDescriptor and Media Player #ISUESS

I m trying to play song by clicking a button in my application. There are two buttons in the application. Each button can play a different song. I allocated all those songs in Assets folder. There are total of two songs in the folder of Assets now.
public class AudioCollective implements MediaPlayer.OnPreparedListener, OnCompletionListener{
static String TAG = "AudioCollective====>";
Context mContext;
MediaPlayer mPlayer;
ArrayList<AssetFileDescriptor> array;
public AudioCollective(Context theContext){
mContext = theContext;
}
public void addSound(int SoundID){
array = new ArrayList<AssetFileDescriptor>();
AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(SoundID);
array.add(afd);
}
public void playSound() {
for (int i =0; i<array.size();i++) {
Log.i(TAG,"preparing audio " + array.get(i) );
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(array.get(i).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
}
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mPlayer != null) {
Log.d(TAG, "releasing audio now");
mPlayer.release();
mPlayer = null;
mediaPlayer.release();
//mediaPlayer = null;
}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.i(TAG, "playing audio now");
mediaPlayer.start();
}
}
meanwhile in my MainActivity :
AudioCollective ac = new AudioCollective();
ac.addSounds(R.raw.na);
playButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
ac.playSound();
}
});
So, the problem is every time I clicked the button, the application play the two songs together instead of playing the required song. anyone can tell me why would this be happen?
Yes it because you are playing both of them at same in for loop.
Update your playSound() method pass value in it as argument.
To play first song pass 0 , To play second song pass 1 .
playSound(0) playSound(1)
public void playSound(int pos) {
Log.i(TAG,"preparing audio " + array.get(pos) );
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(array.get(pos).getFileDescriptor());
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
}
}

I get error (1, 19) when tapping on multiple buttons that play sound

It works for a few buttons, but when I tap about 6 then only some of them work. The ones that don't work give the error (1, -19). I do the media player state wrapper set up, so if I need to use that to get states of my "mp"s, let me know.
public class SoundFile {
public SoundFile(final Activity activity, final String soundfile, int imgButtonId, ArrayList<MediaPlayerStateWrapper> mps) {
this.mp = new MediaPlayerStateWrapper();
try {
this.afd = activity.getAssets().openFd(soundfile + ".mp3");
} catch (IOException e) {
e.printStackTrace();
}
this.allMps = mps;
mps.add(this.mp);
this.position = (ImageButton) activity.findViewById(imgButtonId);
this.position.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mp.reset();
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepareAsync();
mp.start();
}catch (Exception ex){
ex.printStackTrace();
}
....
You have to add an onPreparedListener. Here is what I did and it worked.
try {
mp = new MediaPlayer();
mp.reset();
try {
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mpm) {
mpm.start();
mp.start();
}
});
mp.prepareAsync();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
}

how to loop music from extranal

try to do but can't loop my music from extranal on mobile
i don't know why not look at my code on setOnCompletionListener methods
sorry from my bad english ... Thx for watch
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_effects);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
updatePlaylist();
Uri video = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Music/" + songs.get(0));
mMediaPlayer = MediaPlayer.create(this, video);
mMediaPlayer.start();
mEqualizer = new Equalizer(0, mMediaPlayer.getAudioSessionId());
mEqualizer.setEnabled(true);
setupVisualizerFxAndUI();//อันนี้แสดง คลื่นเสียง
setupEqualizerFxAndUI();
mVisualizer.setEnabled(true);//อันนี้แสดง คลื่นเสียง
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mVisualizer.setEnabled(false);//อันนี้แสดง คลื่นเสียง
i++;
mMediaPlayer.reset();
if (i < songs.size()) {
try {
Uri video = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/Music/" + songs.get(i));
if (video != null) {
mMediaPlayer = MediaPlayer.create(AudioFxActivity.this, video);
// mEqualizer = new Equalizer(0, mMediaPlayer.getAudioSessionId());
mMediaPlayer.start();
}
} catch (Exception ex) {
// report a crash
Log.v(getString(R.string.app_name), ex.getMessage());
}
} else {
// done with media player
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});mMediaPlayer.start();
}
this is my problems

Categories

Resources