Loading Multiple Audio files from SD card - android

I need help/pointer to doc/sample code on how to load multiple audio files from a specific folder on the SD card and have it play a random file back(i think i can figure out the last step if i could just figure out how to load multiple files). Here is my incredibly poorly written app so far, don't judge too harshly as I'm learning as I go.
public class zazenbox extends Activity implements OnClickListener{
File filecheck;
MediaPlayer player;
Button playerButton;
Integer var1;
String path1;
AlertDialog.Builder alertbox;
public void onClick(View v) {
if (v.getId() == R.id.play) {
playPause();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
demoLoad();
playerButton = (Button) this.findViewById(R.id.play);
playerButton.setText(R.string.stop);
playerButton.setOnClickListener(this);
demoPlay();
}
#Override
public void onPause() {
super.onPause();
player.pause();
}
#Override
public void onStop() {
super.onStop();
player.stop();
}
private void demoLoad() {
dirfilecheck();
player = new MediaPlayer();
player.setLooping(true);
try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }
}
private void dirfilecheck() {
filecheck = new File(Environment.getExternalStorageDirectory() + "/zazenbox");
if(filecheck.exists() && filecheck.isDirectory()) {
// load files.
var1 = 1;
path1 = filecheck + "/bm10" + var1 + ".wav";
} else {
// create folder, dl sample loop, and instruct user how to add music/loops.
filecheck.mkdirs();
alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("Please put loopable media in zazenbox on your sdcard.");
alertbox.setNeutralButton("Ok, I will.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "Please plug in your device now", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
}
}
private void demoPause() {
player.pause();
playerButton.setText(R.string.play);
}
private void demoStop() {
player.stop();
playerButton.setText(R.string.play);
}
private void demoPlay() {
player.start();
playerButton.setText(R.string.stop);
}
private void playPause() {
if(player.isPlaying()) {
demoStop();
//demoPause();
//player.release();
var1++;
path1 = filecheck + "/bm10" + var1 + ".wav";
/*try {
player.setDataSource(path1);
player.prepare();
}
catch (IOException e) { e.printStackTrace(); }
catch (IllegalArgumentException e) { e.printStackTrace(); }
catch (IllegalStateException e) { e.printStackTrace(); }*/
//player.start();
//demoPlay();
} else {
//do stuff
demoPlay();
}
}
}

Memory is extremely limited on mobile devices, so you wouldn't want to load songs you're not going to play. So what you should do is find all of the audio files in that folder, and then choose one and THEN load and play it.
You just need to stop the current player and create a new instance.
MediaPlayer player = MediaPlayer.create(this, Uri.parse("Path/To/Media"));
player.start();
// change track
player.stop();
player = MediaPlayer.create(this, Uri.parse("New/Path/To/Media"));
player.start();

Related

Android MediaPlayer stops palyng form assetst after changing image on button from assets

I have problem with playing mp3 from asset folder. When i try to change image on button, mp3 stops playing(not always...)
Error that im getting
W/MediaPlayer-JNI: MediaPlayer finalized without being released
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(enableMusic){
playMusic();
}
...
private void playMusic() {
boolean noAudioFile = false;
Context context = this; // or ActivityNotification.this
MediaPlayer mpMusic = new MediaPlayer();
AssetManager mg2 = getResources().getAssets();
String musicPath = langFolder+audioFolder+"system/Bubble_Bath.mp3";
try {
mg2.open(musicPath);
} catch (IOException ex) {
noAudioFile = true;
}
if(!noAudioFile) {
AssetFileDescriptor descriptor = null;
try {
descriptor = context.getAssets().openFd(musicPath);
} catch (IOException e) {
e.printStackTrace();
}
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
try {
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
}
mpMusic.setVolume(5,5);
try {
mpMusic.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mpMusic.start();
mpMusic.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.start();
}
});
}
public void nextCard(View view) throws IOException {
i++;
if (i==files.length) i=0;
if(i>-1){
Button btnNext = (Button)findViewById(R.id.btnNext);
btnNext.setText("Next");
}
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
findViewById(R.id.btnImage).setBackgroundDrawable(d);
if(files[i].substring(0,1).contains("a") || files[i].substring(0,1).contains("i")){
startFileSound = langFolder + audioFolder + "system/GAME_thisisan.mp3";
}
else if (files[i].substring(files[i].length()-1,files[i].length()).contains("s")){
startFileSound = langFolder + audioFolder + "system/GAME_theseare.mp3";
}
else{
startFileSound = noAudioFileSound;
}
}
When i'll try to comment line below, mp3 is playing with no problem.
Drawable d = Drawable.createFromStream(getAssets().open(categoryPath+"/"+files[i]+".png"), null);
you are loading drawable from asset folder, that is correct. But Don't do in the main thread. Try to do this in different thread.
Don't ever create MediaPlayer like this
MediaPlayer mpMusic = new MediaPlayer();
Use
MediaPlayer.create(context,R.raw.music);
try close descriptor
mpMusic.setDataSource(descriptor.getFileDescriptor(), start, end);
descriptor.close();

AudioRecorder App crashes when I record a second time

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.

Cant play a song using MediaPlayer

Im having some problems playing a simple song (stored in the external SD) using MediaPlayer API. I really dont know what Im doing wrong, cause I havent seen the code error in any other questions and using the developer I havent found it either.
The error Im getting is this:
08-25 00:20:49.514: D/MediaPlayer(26764): mPlayerID = 94
08-25 00:20:49.519: E/MediaPlayer(26764): error (1, -2147483648)
08-25 00:20:49.597: E/MediaPlayer(26764): Error (1,-2147483648)
AudioActivity.java
public class AudioActivity extends Activity{
Audio audioPlayer;
public AudioActivity(){
audioPlayer = new Audio();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set of view where videos and the listView (is there is any) will appear
setContentView(R.layout.audio_player);
Button play = (Button)findViewById(R.id.playButton);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String path = Environment.getExternalStorageDirectory() + "/" + "song";
audioPlayer.loadFile(path);
audioPlayer.prepare();
audioPlayer.play();
}
});
Button pauseResume = (Button)findViewById(R.id.pauseButton);
pauseResume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
audioPlayer.pause();
}
});
Button stop = (Button)findViewById(R.id.stopButton);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
audioPlayer.stop();
}
});
}
}
Audio.class
public class Audio {
MediaPlayer mediaPlayer;
String pathSong;
public Audio(){
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
Log.d("Error", "Arg1: " + arg1 + ".Arg2: " + arg2);
mediaPlayer.reset();
return false;
}
});
}
public void loadFile(String path){
try {
mediaPlayer.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void prepare(){
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play(){
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
public void stop(){
mediaPlayer.stop();
}
public void pause(){
mediaPlayer.pause();
}
public int getDuration(){
return mediaPlayer.getDuration();
}
public MediaPlayer getMediaPlayer(){
return mediaPlayer;
}
public TrackInfo[] getTrackInfo(){
return mediaPlayer.getTrackInfo();
}
}
Any idea? Why the code (1, -2147483648) doesnt appear anywhere? Thanks!

Android: Stop sound files playing at once

In the application I am currently writing, a user is able to select an entry from the database and play the contents of that entry: an entry is made up of a number of sound files (without a limit). In my application, I return the URI locations of the sound files of an entry (which have been stored in my database) in a List. The code is as follows:
public void audioPlayer() {
// set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
DatabaseHandler db = new DatabaseHandler(this);
Entry retrieveEntry = new Entry();
retrieveEntry = db.getEntry();
List<String> path = retrieveEntry.getAudioUri();
path.size();
System.out.println("PATH SIZE: " +path.size());
System.out.println("FILEZ: " + path);
Iterator<String> i = path.iterator();
String myAudio;
int count = 0;
while (i.hasNext()) {
System.out.println(count);
myAudio = i.next();
System.out.println("MY AUDIO: " + myAudio);
MediaPlayer player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
player.stop();
player = MediaPlayer.create(this, Uri.parse(myAudio));
player.start();
count++;
}
}
My users require that there be user input for playing a file - is there a way to play the first file, then wait for the user to press the button, then play the second file, then wait for the user to press the button, etc.? At the moment, when the play button is pressed, all of the sound files that have been returned get played at the same time, rather than one after the other.
Thanks in advance for any help provided!
You can use this class to play a playlist. This will start one audio, when that audio finishes, it will start playing next audio till the end of the list. If you want to play the playlist in looping i.e start first audio after reaching end, then pass isLooping=true in startPlayingPlaylist(list,looping)
AudioPlayer player = new AudioPlayer();
player.startPlayingPlaylist(list, false);
Class
public class AudioPlayer{
MediaPlayer player = null;
ArrayList<String> playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list, boolean looping){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.setLooping(looping);
player.start();
// Set onCompletion listener
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(player.isLooping()==false){
player.release();
player = null;
}
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
Edit:
The class below receives a list of audios, then plays first Audio. It plays next audio when user calls startNextAudio() You can use any one of these according to your requirements
public class AudioPlayer{
MediaPlayer player = null;
ArrayList playlist = null;
int position = 0;
public AudioPlayer() {
super();
// TODO Auto-generated constructor stub
}
public void startPlayingPlaylist(ArrayList<String> list){
playlist = list;
if(player!=null){
player.release();
}
if(playlist!=null && playlist.size()>0){
player = MediaPlayer.create(LMApplicaton.getInstance(),Uri.parse(playlist.get(position)));
player.setWakeMode(LMApplicaton.getInstance(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
// Set onCompletion listener
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
public void startNextAudio(){
position = position+1;
if(position<playlist.size()){
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if(player.isLooping()==true){
position = position%playlist.size();
try {
player.reset();
player.setDataSource(playlist.get(position));
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
Log.i("AudioPlayer","Playlist reached at the end");
}
}
public void pause(){
if(player!=null && player.isPlaying()){
player.pause();
}
}
public void play(){
if(player!=null && player.isPlaying()==false){
player.start();
}
}
public boolean isPlaying(){
return player.isPlaying();
}
public void release(){
if(player!=null){
player.release();
}
}
}
One approach would be to implement the MediaPlayer.OnCompletionListener interface. This gives you the MediaPlayer.onCompletion() callback method which you could use like so:
#Override
public void onCompletion(MediaPlayer mp) {
if (i.hasNext) {
// ...hand mp the next file
// ...show the user the 'play next' button
}
}
Note you also will need to call the MediaPlayer.setOnCompletionListener() method in your setup.

Android: Media files vanish from file system

I am stuck with a weird problem. I have an activity with a MediaPlayer that should play a just recorded audio file. At first the mediaplayer is initialized ok and the file can be played.
When I rotate the screen, the activity is destroyed and then reinitialized for the new orientation. Therefore, I re-initialize the mediaplayer too.
this works a couple of times, but at some point mediaPlayer.setDataSource() throws a NullPointerException because the file is suddenly gone. Sadly, I haven't seen any other error in the logs.
Here are some Code snippets:
player creation:
/**
* Creates and initializes the player with the proper file.
*/
private void createPlayer() {
synchronized (playerMutex) {
player = new MediaPlayer();
player.setLooping(false);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.setOnCompletionListener(this);
}
readGreeting();
}
player initialization:
isPrepared = false;
try {
final File file = new File(audioFilename);
in = new FileInputStream(file);
synchronized (playerMutex) {
player.setDataSource(in.getFD());
}
// using a runnable instead of prepareAsync to not accidentally call pause on media player while preparing
Runnable preparer = new Runnable() {
#Override
public void run() {
try {
synchronized (playerMutex) {
if (player != null) {
player.prepare();
}
}
} catch (Exception ex) {
Log.e(TAG, "Error preparing player for file " + file.getAbsolutePath(), ex);
}
}
};
new Thread(preparer).start();
} catch (Exception ex) {
btnPlayback.setEnabled(false);
Log.e(TAG, "Error preparing player", ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e(TAG, "initPlayer: ", e);
}
}
}
saving instance state...
#Override
protected void onPause() {
synchronized (playerMutex) {
if (isPlaying()) {
getIntent().putExtra(EXTRA_KEY_SEEK, player.getCurrentPosition());
pause();
}
}
setAudioModeBackToNormal();
super.onPause();
}
private void pause() {
synchronized (playerMutex) {
if (isPlaying()) {
player.pause();
}
}
btnPlayback.setVisibility(View.VISIBLE);
btnPause.setVisibility(View.GONE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
final Bundle extras = getIntent().getExtras();
outState.putBundle("extras", extras);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
getIntent().putExtras(savedInstanceState.getBundle("extras"));
}
cleanup:
private void stopPlayerAndFreeResources() {
synchronized (playerMutex) {
isPrepared = false;
if (player != null) {
player.stop();
player.release();
player = null;
}
}
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
Log.e(TAG, "Unexpected error", e);
}
}
}
Maybe I'm looking at the problem from the wrong angle and it has nothing to do with player. Has anybody ever had issues with disappearing files?
I had playlist files disappear once. The cause of the problem turned out to be certain media players that had an option to manage my playlists. In this case manage meant deleting the playlists I already had :(

Categories

Resources