Implement sounds in an android application - android

I am developing a game application in android. I have designed all the views and implemented all the functionality. Now in the last screen I have to play sounds in android. Can anybody tell me how to pursue with it?

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp.start();
And then you get all the start/stop/reset/pause/release methods from mp.

Just place the sound file in /res/raw (after creating the folder) and then use MediaPlayer to init, start and then stop playing the sound. MediaPlayer documentation can be found here.
HTH,
Sriram.

I would suggest SoundPool for seamless playback in android because
mediaPlayer first loads the whole sound data in memory than play, so it produces some lag when we switch among sounds frequently.
SoundPool is a better option with small size sound file, and produces best result with .ogg media file.
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.sound, 1);
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}

From Android Developer page: http://developer.android.com/guide/topics/media/index.html
Playing from a Raw Resource Perhaps
the most common thing to want to do is
play back media (notably sound) within
your own applications. Doing this is
easy:
Put the sound (or other media
resource) file into the res/raw folder
of your project, where the Eclipse
plugin (or aapt) will find it and make
it into a resource that can be
referenced from your R class Create an
instance of MediaPlayer, referencing
that resource using
MediaPlayer.create, and then call
start() on the instance:
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();
To stop playback, call stop().
If you wish to later replay
the media, then you must reset() and
prepare() the MediaPlayer object
before calling start() again.
(create() calls prepare() the first
time.)
To pause playback, call pause().
Resume playback from where you paused
with start().
Playing from a File or Stream You can
play back media files from the
filesystem or a web URL:
Create an instance of the MediaPlayer
using new Call setDataSource() with a
String containing the path (local
filesystem or URL) to the file you
want to play First prepare() then
start() on the instance:
Like this
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();

By using Media Player you can achieve this.
here is the steps::
1.- Create a new folder called "raw" inside "debug" folder. To create it right clic on "debug" folder > new > directory > and in name it "raw" :
To add files just drag the .wav/.mp3 files to "raw" folder.
2.- Import media player:
import android.media.MediaPlayer;
3.- Declare MediaPlayer global variable(s):
public MediaPlayer mp1;
4.- Inside onCreate method, asign the corresponding sounds:
mp1 = MediaPlayer.create(MainActivity.this, raw.my_sound_name);
5.- Finally, you can use methods...
mp1.start() / mp1.stop() / mp1.pause()

Related

Set AudioStreamType for an audio file played from Resource (raw folder)

[First App] I am creating a sort of Alarm app that allows user to select alarm sound from either sd-card or app-supplied sounds. Since, the app essentially plays alarms, I want the volume to be 'alarm volume' of the device. I am able to achieve this for sd card sounds. But, I am unable to setAudioStreamType for raw resource sounds.
I am using following code :
MediaPlayer m_player = new MediaPlayer();
m_player.setAudioStreamType(AudioManager.STREAM_ALARM);
switch (bin_name) { //bin_name = various user selectable music files
default:
m_player = MediaPlayer.create(context, R.raw.blu);
break;
}
m_player.setLooping(true);
m_player.start();
My blu.mp3 plays at media volume only. Upon checking the documentation for MediaPlayer.create(Context context, int resid), I found this :
Note that since prepare() is called automatically in this method, you cannot change the audio stream type (see setAudioStreamType(int)), audio session ID (see setAudioSessionId(int)) or audio attributes (see setAudioAttributes(AudioAttributes) of the new MediaPlayer.
I also tried finding code samples for above method but none of them showed how to set AudioStreamType to AudioManager.STEAM_ALARM. I will accept answers with alternative ways that simply play the sound with infinite loop. How to achieve this ?
As the documentation you are referring to says, you must create and prepare the MediaPlayer yourself. Haven't tried with the STREAM_ALARM but I'm using following snippet to play on STREAM_VOICE_CALL
Uri uri = Uri.parse("android.resource://com.example.app/" + R.raw.hdsweep);
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepare();
mMediaPlayer.start()

sounds not playing with mediaplayer after playing some sounds

I'm developing an android application which is collection of 100 sound effects.
After I play for instance 25 of the sounds, I can't play anymore and I have to close the application and wait for some minutes then open the application and now I can play other sounds.
final MediaPlayer mp81 = MediaPlayer.create(MainActivity.this, R.raw.a81);
I play the sound using the below code:
mp81.start();
I stop the playing sound using the below code:
mp81.seekTo(0);
I also used stop() method but the problem were still existing.
is there any other method i have to add?
Please note: consider using SoundPool for playing short sounds.
Regarding your use-case: you initialize your MediaPlayer instance using the static create() method which means you create a new MediaPlayer object for each sound instead of reusing an existing instance and just changing the data source. This might negatively affect the performance of your app. I suggest that you create an array of paths to your sounds and then instantiate the MediaPlayer like this:
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(yourArray[x]);
mp.prepare();
mp.start();
} catch(Exception e){
e.printStackTrace();
}
Consult the MediaPlayer Document for more information.

Prevent MediaPlayer from play all mp3 files in the folder automatically

I'm from Taiwan and my English is pretty basic, thanks for your forgiveness.
I built a iPad app and published to App Store, which is a kind of communicating board (AAC for the person who has difficult on speaking). It has several buttons on main view and when user touch up one, the app will play a mp3 sound corresponding to that button. I've put all mp3 files on a folder and determining which one to play dynamically at run-time.
Recently I'm working on build the Android version of this app, but I meet a problem that is when I touch up one button on the view, the MediaPlayer play not only the corresponding one but keep playing all the rest mp3 files on the folder continuously. It doesn't happen on the development of iPad version. Any one can help me to resolve this problem and set the MediaPlayer up to working appropriately?
PS. I put all MP3 files on some sub-folders and put them on the "assets" folder. It because for some reasons, all mp3 files are using numeric file name (ex. 0123223.mp3), and which MP3 to play is according to which button user touched up, so I can't use R.raw.0123223 not only because the R class can't has a member named in numeric, but also the target mp3 file can only determining at run-time instead of compile-time, so I can't use the res/raw folder.
My code is as following:
private void PlayMP3(String mp3File) throws IOException {
AssetFileDescriptor afd = this.getAssets().openFd(mp3File);
MediaPlayer player = new MediaPlayer();
player.setOnCompletionListener(new OnCompletionListener(){
public void onCompletion(MediaPlayer mp) {
System.out.println(mp.getAudioSessionId() + " finished.");
}
});
player.setDataSource(afd.getFileDescriptor());
player.setLooping(false);
player.prepare();
player.start();
}
the parameter "mp3file" of PlayMP3 is a concatenated string of mp3 file path, according to the button user touched up.
Many thanks!
Your version would work if you had only that one file in the assets directory. The asset directory contents 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 as if they are one file.
You can accomplish what you want by using setDataSource with more arguments:
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
This will allow you to define the limits of the player and only play the song you specify in your string mp3File.
You did not post some code.
First step is to insert your sound file into the raw folder
Then, you need only a few lines of code:
MediaPlayer mediaPlayer = null;
mediaPlayer = MediaPlayer.create(getBaseContext(), R.raw.mysoundfile);
mediaPlayer.start();
When the application is closing, dont forget to "release" your media player:
mediaPlayer.release();
mediaPlayer = null;

Android : how to play multiple audios using single media player object

I need to create only one media player object Mediaplayer mp = new Mediaplayer();
Using this I need to play multiple audio files one after the other for that i am using handler
and getting the duration.
If i create multiple media player objects it shows error(1, -17)
I also need to display images related to audio files.
Did you rule out SoundPool?
http://developer.android.com/reference/android/media/SoundPool.html
It typically good for short audio clips.
Implement the OnCompletionListener and register it with your MediaPlayer instance.
After the media has been played out it will call this callback method onCompletion
void onCompletion(MediaPlayer mp){
//Here you stop it.
mp.stop();
//Reset the data source path to the new file
mp.setDataSource(<uri>);
mp.prepare(); // or mp.prepareAsync();
// start the mediaplayer after the prepare has completed.
}
Release the mediaplayer instance once you are done playing all the files.

One Android MediaPlayer Object plays several sounds at once

I have ONE object MediaPlayer mediaplayer. I use it to play different sounds, one after another.
mediaplayer = MediaPlayer.create(context, ResIdMusicONE);
mediaplayer.start();
// some user input
mediaplayer.release();
mediaplayer = null;
// some other user input
mediaplayer = MediaPlayer.create(context, ResIdMusicTWO);
mediaplayer.start();
// some user input
mediaplayer.release();
mediaplayer = null;
Sometimes is works fine. But sometimes the two sounds are played at the same time. And at positions, where mediaplayer should already have been released and be equal null.
Thanks for the help.
If I were you I would use the SoundPool class for this. With SoundPool you can set the number of streams to play at the same time, so by setting that to 1 you can just call play() over and over and the most recent call to play() will be the only sound that you hear.
Take a look at my post a while back. It has an example of the SoundPool class in the question.
Edit:
Have you tried creating a new instance and calling the prepare() every time you want to start a new sound?
mediaplayer = new MediaPlayer();
mediaplayer.setDataSource(path);
mediaplayer.prepare();
mediaplayer.start();
Though actually now that I think about it, I'm pretty sure you only need to do that if you are using a file from the sdcard not from your resources... Hmmm.

Categories

Resources