I need to play random sound out of 300 sounds placed in assets folder.
While implementing the problem I am getting is that its always playing the first sound from assets on button click.
MediaPlayer player;
AssetFileDescriptor descriptor;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.machine);
player = new MediaPlayer();
playSound = (ImageButton)findViewById(R.id.button_play);
AssetManager aMan = this.getAssets();
try
{
filelist = aMan.list("");
} catch (IOException e1) {
e1.printStackTrace();
}
playSound.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(filelist.length);
try
{
String mediaFile = filelist[randomInt];
descriptor = getAssets().openFd(mediaFile);
player.setDataSource(descriptor.getFileDescriptor(),descriptor.getStartOffset(),descriptor.getLength());
descriptor.close();
player.prepare();
player.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
Try changing this line:
filelist = aMan.list("");
to this:
filelist = aMan.list("/assets");
Related
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();
I want to play random sounds from assets/ folder in my project.
What's wrong with that code? Help me please
Here's my code:
MediaPlayer player;
AssetFileDescriptor descriptor;
private String[] filelist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
Button bTutorial1 = (Button) findViewById(R.id.tutorial1);
AssetManager aMan = this.getAssets();
try {
filelist = aMan.list("mysounds/");
// OR
// filelist = aMan.list("/");
} catch (IOException e1) {
e1.printStackTrace();
{
}
bTutorial1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(filelist.length);
try {
String mediaFile = filelist[randomInt];
descriptor = getAssets().openFd(mediaFile);
player.setDataSource(descriptor.getFileDescriptor(),
descriptor.getStartOffset(),
descriptor.getLength());
descriptor.close();
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
After click on the button nothing sound is playing. Help me!
No errors displays.
Try this Mediaplayer constructor:
MediaPlayer player = MediaPlayer.create(Context context, Uri uri);
uri = Uri.parse("file:///android_asset/mysounds/music.mp3");
i'm developing a little quizz app and i would like to play sound depending on if the user answers the question correctly or not.
I've got many sound files in "assets/".
What I would like to do is to play just one of these sounds.
I've been able to play the sound, but not only one, both sound (correct and incorrect) are played one after the other.
How can i play just one?
Here's my source:
public void audioPlayer(){
//set up MediaPlayer
mp = new MediaPlayer();
try {
String mp3File = "correct.mp3";
AssetManager assetMan = getAssets();
FileInputStream mp3Stream = assetMan.openFd(mp3File).createInputStream();
mp.setDataSource(mp3Stream.getFD());
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Put your sound files i.e fail and applause in raw folder and use the following code :
private AssetFileDescriptor sPlaySoundDescriptor = null;
private AssetFileDescriptor sFailSoundDescriptor = null;
private MediaPlayer mp = null;
public static final int FAIL_SOUND = 1;
public static final int APPLAUSE_SOUND = 2;
public void audioPlayer(int soundType){
//set up MediaPlayer
mp = new MediaPlayer();
AssetFileDescriptor soundFileDescriptor = null;
try {
if (sFailSoundDescriptor == null) {
sFailSoundDescriptor = context.getResources().
openRawResourceFd(R.raw.fail);
}
if (sApplauseSoundDescriptor == null) {
sApplauseSoundDescriptor = context.getResources().
openRawResourceFd(R.raw.applause);
}
switch (soundType) {
case FAIL_SOUND:
soundFileDescriptor = sFailSoundDescriptor;
break;
case APPLAUSE_SOUND:
soundFileDescriptor = sApplauseSoundDescriptor;
break;
}
mp.reset();
mp.setDataSource(soundFileDescriptor.getFileDescriptor(),
soundFileDescriptor.getStartOffset(),
soundFileDescriptor.getDeclaredLength());
mp.prepare();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.seekTo(0);
player.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
OK so I have a Woohoo.mp3 in my "assets" folder of my project
also after packing the .apk I do find it residing in the assets folder
audioPlayer("file:///android_assets/Woohoo.mp3");
or
audioPlayer("file://android_assets/Woohoo.mp3");
did not work...
here is my audioPlayer method:
public void audioPlayer(String fileName){
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
Uri uri = Uri.parse(fileName);
try {
AssetManager manager = getBaseContext().getAssets();
AssetFileDescriptor descriptor = manager.openFd(fileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mp.setDataSource(descriptor.getFileDescriptor(), start, end);
//File file = new File(fileName);
//FileInputStream fis = new FileInputStream(file);
//mp.setDataSource(getBaseContext(),uri);
//mp.setDataSource(fis.getFD());
mp.prepare();
mp.start();
} catch(FileNotFoundException e){
Toast.makeText(getBaseContext(),
e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
} catch (IOException e) {
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
};
}
I've been looking at this site and some other forums for few hours and tried a few methods and NONE of them worked for me....I wonder where I did wrong here... thanks
For using Assets u have to give only the FileName not the FilePath.
Try using only Woohoo.mp3
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();
}