I have a list of audio files like this,
int music_numbers[] = { R.raw.one, R.raw.two, R.raw.three, R.raw.four,
R.raw.five, R.raw.six, R.raw.seven, R.raw.eight, R.raw.nine };
I need to play this one by one - when i send 100 to this play_numbers method - i am intend to play digit wise..
I have done this - but i unable to do this one after another..
private void _play_numbers(final String i) {
// TODO Auto-generated method stub
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.start();
mPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mPlayer.stop();
myDigit = i.charAt(1) + "";
_function_play_file(Integer.parseInt(myDigit));
}
});
}
in _function_play_file - i have this
void _function_play_file(int files) {
switch (files) {
case 0:
mPlayer = MediaPlayer.create(this, music_numbers[0]);
mPlayer.start();
case 1:
mPlayer = MediaPlayer.create(this, music_numbers[1]);
mPlayer.start();
case 2:
mPlayer = MediaPlayer.create(this, music_numbers[2]);
mPlayer.start();
case 3:
mPlayer = MediaPlayer.create(this, music_numbers[3]);
mPlayer.start();
case 4:
mPlayer = MediaPlayer.create(this, music_numbers[4]);
mPlayer.start();
case 5:
mPlayer = MediaPlayer.create(this, music_numbers[5]);
mPlayer.start();
case 6:
mPlayer = MediaPlayer.create(this, music_numbers[6]);
mPlayer.start();
case 7:
mPlayer = MediaPlayer.create(this, music_numbers[7]);
mPlayer.start();
case 8:
mPlayer = MediaPlayer.create(this, music_numbers[8]);
mPlayer.start();
case 9:
mPlayer = MediaPlayer.create(this, music_numbers[9]);
mPlayer.start();
case 10:
mPlayer = MediaPlayer.create(this, music_numbers[10]);
mPlayer.start();
}
}
You need to set an onCompletionListener to each and start the next one on completion.
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// Code to start the next audio in the sequence
}
});
The best way to achieve this is to create a class that implements OnCompletionListener which handles the onCompletion and receives the next file to play. This way you can instantiate it nicely in your code.
Of course, don't forget your break; in the cases above.
Use a queue for holding the numbers to be played.
private void _play_numbers(final String i) {
// e.g '100': put '1', '0', '0' in a Queue after converting to digits
Queue queue = new LinkedList();
//Use the add method to add items.
myDigit = // remove next digit from queue..
_function_play_file(myDigit);
}
void _function_play_file(int files) {
switch(files) {
case 0:
mPlayer = MediaPlayer.create(PlayFileActivity.this, R.raw.payment);
mPlayer.setOnCompletionListener(completeListener );
mPlayer.start();
break;
.....
}
OnCompletionListener completeListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
myDigit = // remove next digit from queue..
if (myDigit != -1) // if queue is not empty..
_function_play_file(myDigit);
}
});
}
This code works for me,but i place the audio files in assets folder:
//define a variable to be used as index.
int audioindex = 0;
//Extract the files into an array
String[] files = null;
files = assetManager.list("audiofiles");
mp.setOnCompletionListener(new OnCompletionListener(){
// #Override
public void onCompletion(MediaPlayer arg0) {
// File has ended, play the next one.
FunctionPlayFile(files[audioindex]);
audioindex+=1; //increment the index to get the next audiofile
}
});
This is working code for playing songs in continue loop
public class MainActivity extends Activity
{
private int[] tracks = {R.raw.explosion,R.raw.pianothingy_one,R.raw.car_horn_x};
int mCompleted = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mp = MediaPlayer.create(this, tracks[0]);
mp.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mCompleted++;
mp.reset();
if (mCompleted < tracks.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted>=tracks.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(tracks[mCompleted]);
if (afd != null)
{
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp.prepare();
mp.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp.release();
mp = null;
}
}
});
mp.start();
use PlayMedia Like this
int[] soundIDs = {R.raw.yes, R.raw.eat};
PlayMedia playAudio = new PlayMedia(context,soundIDs);
playAudio.execute();
and define PlayMedia Class Like this
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.util.Log;
public class PlayMedia extends AsyncTask<Void, Void, Void> {
private static final String LOG_TAG = PlayMedia.class.getSimpleName();
Context context;
private MediaPlayer mediaPlayer;
int[] soundIDs;
int idx =1;
public PlayMedia(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
public PlayMedia(final Context context, final int[] soundIDs) {
this.context = context;
this.soundIDs=soundIDs;
mediaPlayer = MediaPlayer.create(context,soundIDs[0]);
setNextMediaForMediaPlayer(mediaPlayer);
}
public void setNextMediaForMediaPlayer(MediaPlayer player){
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(soundIDs.length>idx){
mp.release();
mp = MediaPlayer.create(context,soundIDs[idx]);
setNextMediaForMediaPlayer(mp);
mp.start();
idx+=1;
}
}
});
}
#Override
protected Void doInBackground(Void... params) {
try {
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.e(LOG_TAG, "", e);
} catch (SecurityException e) {
Log.e(LOG_TAG, "", e);
} catch (IllegalStateException e) {
Log.e(LOG_TAG, "", e);
}
return null;
}
}
For me the issue was that I was calling mediaPlayer.prepare() without first calling mediaPlayer.reset().
All good now.
MediaPlayer mediaplayer = new MediaPlayer();
setSound(file );
try {
if(mediaplayer != null)
{
mediaplayer.stop();
mediaplayer.release();
}
mediaplayer.setDataSource(getResources().openRawResourceFd(file)
.getFileDescriptor());
mediaplayer.prepare();
mediaplayer = MediaPlayer.create(getBaseContext(), now);
mediaplayer.start();
mediaplayer.setLooping(false);
mediaplayer.setLooping(true); //sequence playing
} catch (NullPointerException e) {
e.printStackTrace();
}
Related
How do I play an audio from raw folder on button click? Here, I'm using recyclerview to show the list of audios. But when click play, it doesn't play any sound.
private Button btnPlay;
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(ss.getSoundURI());
mp.prepare();
mp.start();
} catch (Exception e){
e.printStackTrace();
}
}
});
You can use this function:
public void playSound(final String fileName) {
MediaPlayer mpPlayer = null;
try {
int fileId = getResources().getIdentifier(fileName, "raw", getPackageName());
mpPlayer = MediaPlayer.create(this, fileId);
mpPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mpPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (Exception e) {
e.printStackTrace();
if (mpPlayer != null)
mpPlayer.release();
}
}
NOTE: use file name without file extension. for example if your file name is file1.wav you should send file1 as a file name to function NOT file1.wav .
NOTE: In first line I defined the mpPlayer and initialize it because i want to use it in the catch block.
im newbie here, can you help me?? i want to play all song in my raw folder sequentially, after all song finished playing i want no looping.
i have tried this code but it keeps looping after allsong playing
{
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play();
}
});
}
private void play () {
soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[soundke]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
it still keeps looping after all song playing. i want not looping after all song playing, thanks for your helping
int [] sound;
int soundke = 0;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kubus);
sound = new int[] {R.raw.swoosh2, R.raw.swoosh1, R.raw.swoosh2};
mediaPlayer = MediaPlayer.create(kubus.this, sound[0]);
mediaPlayer.setLooping(false);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(soundke < sound.length-1){
play(++soundke);
}else{
soundke=0;
mediaPlayer.stop();
}
}
});
}
private void play (int track) {
//soundke = (soundke + 1) % 3;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(sound[track]);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.setLooping(false);
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
} catch (IOException e) {
}
}
I need to play multiple (correct :2 ) mp3 files loaded from my assets when a button is clicked. If the button is again clicked 2 new songs should be played and the old ones should be stopped immidiatelly.The process is on going...
At the moment I have achieved this by stupidly creating 2 mediaPlayer instances in 2 separate methods that basically have the same body .
The caller is an onTouch method and ,within it, first I call method 1 ,then sleep for 2 secs ,then call method 2. I m sure there must be a way for this to be more elegant code? For example I have implemented some listeners that are just sitting there (Actually tried to make this work but totally screwed up with Illegal States all over the place ). Ideally I would like to use 1 MediaPlayer and one method for playing every sound in my app.
int carouzelIndex = 0
#Override
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
...
if (e.getAction() == MotionEvent.ACTION_UP) {
carouzelIndex++;
Assets.playMusic1("music1.ogg",false);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assets.playMusic2("music2.ogg",false);
}
}
}
}
Now my player methods 1 and 2 (playMusic1() and playMusic2() )are the same. Both are instansiating different MediaPlayers and for the shake of simplicity I write just one copy in the post
Public class Assets
MediaPlayer mediaPlayer;
public static void playMusic(String filename, boolean looping) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
For immediate playback you need two MediaPlayer set up and chained together via OnCompletionListener
You can do it like this:
Note that I also deleted some unnecessary overrides, you might add them again if you need them.
Public class Assets{
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
boolean mediaplayer2prepared = false;
boolean mediaplayer1finished = false;
public static void playMusic(String filename, boolean looping, String filename2, boolean looping2) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 == null) {
mediaPlayer2 = new MediaPlayer();
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
mediaplayer2prepared = false;
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 != null) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = new MediaPlayer();
mediaplayer2prepared = false;
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
if(mediaplayer2prepared)
mediaplayer2.start();
mediaplayer1finished = true;
}
});
mediaPlayer.prepareAsync();
afd2 = GameMainActivity.assets.openFd(filename2);
mediaPlayer2.setDataSource(afd2.getFileDescriptor(),
afd2.getStartOffset(), afd2.getLength());
afd2.close();
mediaPlayer2.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
mediaplayer2prepared = true;
if(mediaplayer1finished && !mp.isPlaying()){
mp.start();
}
}
});
mediaPlayer2.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To start both mediaplayers in succession simply do Assets.playMusic("music1.ogg",false, "music2.ogg",false);
You can try something like this. Use a single mediaplayer in a single thread. It is an asynchronous operation so it will go on also if the thread is paused. I think it would work.
private Thread t = null;
private MediaPlayer mediaPlayer;
...
Button b=findViewById(R.id.yourButtonId);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//if button had previously clicked stop audio reproduction
if(mediaPlayer.isPlaying()) mediaPlayer.stop();
if(t.isAlive()) t.stop();
String[] files;
//Here you have to set your filenames in the array
...
...
//Now play that audio
playMusic(files, false);
}
});
...
protected static void playMusic(String[] files, boolean looping){
AssetFileDescriptor afd = null;
Log.e("Assets", "Playing music");
t=new Thread(){
#Override
public void run(){
//Initialize mediaPlayer
for(String filename:files){
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
afd = GameMainAcivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
if(!mp.isPlaying()) mp.start();
}
});
//while audio is playing wait in this position
while(mediaPlayer.isPlaying()){
this.wait(100);
}
//now loop can restart with the other filename that has
//to be reproduced
}
}
};
t.start();
}
I am trying to play an audio file when the app started, but I am getting an error says that start called in state 1 Error (-38,0), here is my code:
public void audioPlayer(){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.create(this, R.raw.music);
onPrepared(mp);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onPrepared(MediaPlayer mp) {
mp.start();
}
public void audioPlayer(){
MediaPlayer mp = new MediaPlayer();
mp.setOnPreparedListener(mListener);
try {
mp.setDataSource(this, R.raw.music);
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
private OnPreparedListener mListener=new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};
i'm adding multiple audio files using
try {
MediaPlayer mp = MediaPlayer.create(context, R.raw.play);
audioArr[0] = mp;
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
and releasing media in a function as
for (MediaPlayer media : audioList) {
if (media != null) {
if(media.isPlaying())
media.stop();
media.release();
media = null;
}
}
stil i'm not able to play multiple audio file in my application,first time playing with audio,so kindly guide
Try this :
void addSongs()
{
File songs = new File(sdPath); //sdPath is the path of your audio files
if(songs.listFiles(new SongFilter()).length > 0)
{
for(File file : songs.listFiles(new SongFilter()))
{
vector.add(file.getName());
}
arrayAdapter.setNotifyOnChange(true); //arrayAdapter Array Adapter
songList.setAdapter(arrayAdapter); //songList is a ListView
}
}
SongFilter Class like this :
class SongFilter implements FilenameFilter
{
public boolean accept(File dir, String filename)
{
return (filename.endsWith(".mp3"));
}
}
buttonSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// play another sound here.do your stuff whatever you want to do
mp.stop();
}
});
public class AudioActivity extends Activity implements MediaPlayer.OnCompletionListener {
int [] songs;
MediaPlayer mediaPlayer;
int current_index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {##}
private void start(){
songs= new int[] {R.raw.s1,R.raw.s2,R.raw.s3,R.raw.s4};
mediaPlayer = MediaPlayer.create(this, songs[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
**// This is the completion listener registered with mediaplayer instance.**
playNextSong();
}
private void playNextSong()
{
current_index = (current_index +1)% songs.length;
AssetFileDescriptor afd = this.getResources().openRawResourceFd(songs[current_index]);
if(current_index!=0){
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.start();
afd.close();
}
catch (IllegalArgumentException e){}
catch (IllegalStateException e){}
catch (IOException e){}
}else{
mediaPlayer.stop();
}
}
}