Play audio file from the assets directory - android

I have the following code:
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();
The problem is that, when I run this code, it starts playing all the audio files in the assets directory, in alphabetical order instead of just playing the audio file I requested. What am I doing wrong? Is there a better way to play audio files from the assets directory?
Follow-up question:
Is there a difference between keeping audio files in the assets directory and keeping them in the res/raw directory? Besides the fact that they don't get ids if they are in the assets directory. If I move the audio files to the res/raw folder then I have a problem with reusing MediaPlayers because there is no id parameter for setDataSource(). I can't find a good guideline for handling this kind of problem.

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
Your version would work if you had only one file in the assets
directory. The asset directory contents are not actually 'real files'
on disk. All of them are put together one after another. So, if you do
not specify where to start and how many bytes to read, the player will
read up to the end (that is, will keep playing all the files in assets
directory)

This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}

Here my static version:
public static void playAssetSound(Context context, String soundFileName) {
try {
MediaPlayer mediaPlayer = new MediaPlayer();
AssetFileDescriptor descriptor = context.getAssets().openFd(soundFileName);
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}

start sound
startSound("mp3/ba.mp3");
method
private void startSound(String filename) {
AssetFileDescriptor afd = null;
try {
afd = getResources().getAssets().openFd(filename);
} catch (IOException e) {
e.printStackTrace();
}
MediaPlayer player = new MediaPlayer();
try {
assert afd != null;
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
}

Fix of above function for play and pause
public void playBeep ( String word )
{
try
{
if ( ( m == null ) )
{
m = new MediaPlayer ();
}
else if( m != null&&lastPlayed.equalsIgnoreCase (word)){
m.stop();
m.release ();
m=null;
lastPlayed="";
return;
}else if(m != null){
m.release ();
m = new MediaPlayer ();
}
lastPlayed=word;
AssetFileDescriptor descriptor = context.getAssets ().openFd ( "rings/" + word + ".mp3" );
long start = descriptor.getStartOffset ();
long end = descriptor.getLength ();
// get title
// songTitle=songsList.get(songIndex).get("songTitle");
// set the data source
try
{
m.setDataSource ( descriptor.getFileDescriptor (), start, end );
}
catch ( Exception e )
{
Log.e ( "MUSIC SERVICE", "Error setting data source", e );
}
m.prepare ();
m.setVolume ( 1f, 1f );
// m.setLooping(true);
m.start ();
}
catch ( Exception e )
{
e.printStackTrace ();
}
}

this works for me:
public static class eSound_Def
{
private static Android.Media.MediaPlayer mpBeep;
public static void InitSounds( Android.Content.Res.AssetManager Assets )
{
mpBeep = new Android.Media.MediaPlayer();
InitSound_Beep( Assets );
}
private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
{
Android.Content.Res.AssetFileDescriptor AFD;
AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
AFD.Close();
mpBeep.Prepare();
mpBeep.SetVolume( 1f, 1f );
mpBeep.Looping = false;
}
public static void PlaySound_Beep()
{
if (mpBeep.IsPlaying == true)
{
mpBeep.Stop();
mpBeep.Reset();
InitSound_Beep();
}
mpBeep.Start();
}
}
In main activity, on create:
protected override void OnCreate( Bundle savedInstanceState )
{
base.OnCreate( savedInstanceState );
SetContentView( Resource.Layout.lmain_activity );
...
eSound_Def.InitSounds( Assets );
...
}
how to use in code (on button click):
private void bButton_Click( object sender, EventArgs e )
{
eSound_Def.PlaySound_Beep();
}

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();

Create song list from expansion zipfile for oncompletionlistener

I have been trying to do it in different ways, but all the "lists" want int or string and I have Assetfiledescriptor stuff to work with.
How can I create a list of certain mp3 files, which are located in the activity expansionfile, that I can use for oncompletionlisteners, etc?
They all work fine individually, but I want to play them after each other.
Here are a few files that I would use:
AssetFileDescriptor dfFn01, dfFn02, dfFn03 = null;
dfFn01 = expansionFile.getAssetFileDescriptor("l1r_df_l6.mp3");
dfFn02 = expansionFile.getAssetFileDescriptor("l1r_df_l7.mp3");
dfFn03 = expansionFile.getAssetFileDescriptor("df_jp_l1r03.mp3");
Here is the player that starts from a buttonclick:
public void setWholeEngAudio(AssetFileDescriptor fd) throws IllegalStateException {
try {
stopPlayers();
wholeTextPlayer = new MediaPlayer();
wholeTextPlayer.reset();
wholeTextPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
try {
wholeTextPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
wholeTextPlayer.start();
seekBar.setProgress(0);
seekBar.setMax(100);
updateSeekBar();
setThumbState();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks

Working with MP3 sound in Processing for Android ( need to stop )

I am developing an app for Android devices using Processing 2.0, now I have playMP3(); function but need to stop the sound using stopMP3();. I tried everything but what is the best way to load an mp3 and play/stop using processing?, snd.stop(); within the stopMP3 function does not work...
import android.media.*;
import android.content.res.*;
...
MediaPlayer snd;
...
void setup()
{
MediaPlayer snd = new MediaPlayer();
}
...
void playMP3()
{
try {
AssetManager assets = this.getAssets();
AssetFileDescriptor fd = assets.openFd("loop1.mp3");
snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
snd.prepare();
snd.start();
snd.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void stopMP3(){
????
}
this is a simple sample for media player
private MediaPlayer m_Player;
//Start Play Function
private void startPlaying() {
m_Player = new MediaPlayer();
m_Player.setOnCompletionListener(onComplete);
try {
if(m_Player.isPlaying())
stopPlaying();
m_Player.setDataSource(m_FileName);
m_Player.prepare();
m_Player.start();
} catch (IOException e) {
}
}
//Stop Play Function
private void stopPlaying() {
m_Player.stop();
m_Player.reset();
m_Player = null;
}
//and this is onComplete Listener
MediaPlayer.OnCompletionListener onComplete = new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stopPlaying();
}
};
i hope it's helping you

Android, How to play WAV file programmatically

I already have a .wav file in my directory.
at the same time i need to play it together with a mp3 file.
I used,
String recordedFile = "/storage/sdcard0/PINOYKARAOKE/1373597371359.wav";
MediaPlayer recordedSong = new MediaPlayer();
try{
recordedSong = MediaPlayer.create(ctx, Uri.fromFile(recordedFile));
recordedSong.prepare();
recordedSong.start();
}
catch(Exception e){
}
error:
creation failed and it throws IOException
Try to create raw folder and put your file there, use this
public void number(int num, Context ctx) {
AssetManager am;
try {
am = ctx.getAssets();
AssetFileDescriptor afd = am.openFd("android.resource://"+getPackageName+"/"+R.raw.your_file_name);
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
afd.getLength());
player.prepare();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
player.setLooping(false);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I've tried #aangwi answer but got FileNodeFoundException
final AssetFileDescriptor afd = myactivity.getResources().openRawResourceFd(R.raw.your_file);
final FileDescriptor fileDescriptor = afd.getFileDescriptor();
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(fileDescriptor, afd.getStartOffset(),
afd.getLength());
player.setLooping(false);
player.prepare();
player.start();
} catch (IOException ex) {
LOGGER.error(ex.getLocalizedMessage(), ex);
}
This works for me (Kotlin):
val mediaPlayer = MediaPlayer.create(
context,
R.raw.sound)
mediaPlayer.start()

Android Audio Question

I have several audio files in the res/raw folder.
When I run the following code I was assuming that just the "sound1" file would be played, instead all of the files in the folder get played one after another, not just "sound1".
MediaPlayer mp = MediaPlayer.create(this, R.raw.sound1);
try {
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
What am I missing?
Thanks for any help!
You can try this way.
static MediaPlayer mpBackground = new MediaPlayer();
mpBackground = MediaPlayer.create(this, R.raw.music);
mpBackground.start();
Use SoundPool instead if they are short sound clips... I ran into alot of issues using the Mediaplayer for playing short sounds. I store my sounds in the assets folder instead of res/raw... but you can get the same results. Here is some code.
private int BUZZ = sound_load("sounds/buzz.mp3");
private SoundPool _sounds = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);
private int sound_load(String fname) {
AssetManager am = getAssets();
try {
AssetFileDescriptor fd = am.openFd(fname);
int sid = _sounds.load(fd.getFileDescriptor(), fd.getStartOffset(),
fd.getLength(), 1);
return sid;
} catch (IOException e) {
}
return 0;
}
private void sound_play(int sid) {
_sounds.play(sid, (float) 1.0, (float) 1.0, 0, 0, (float) 1.0);
}
Then to play a sound I just call it like this:
sound_play(BUZZ);

Categories

Resources