Android: Loop sound file in oncreate - android

I want to loop my sound mp3 file in onCreate() method infinitely.
My code in onCreate method is as follows :
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7);
mMediaPlayer.setVolume(0.2f, 0.2f);
Log.e("beep","started1");
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7);
mMediaPlayer.start();
}
});
mMediaPlayer.setLooping(true);
Log.d("beep","started0");
mMediaPlayer.start();
But this code plays my audio file only once. Please help !!
Thanks in advance.

Try this
void playMp3()
{
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7);
mMediaPlayer.setVolume(0.2f, 0.2f);
Log.e("beep","started1");
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
playMp3();
}
});
Log.d("beep","started0");
mMediaPlayer.start();
}
And If your sound file is small then SoundPool instead of MediaPlayer
private void initializeSoundPool(){
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
playFile();
initializeSoundPool();
}
});
soundID = mSoundPool.load(this, R.raw.glassbreak, 1);
}
call this methode
private void playFile(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (loaded) {
mSoundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}

Related

Toggle between earphone and speakerphone not working, with MediaPlayer and AudioManager

I'm using MediaPlayer to play audio via an AsyncTask, and using AudioManager to set the stream. On a specific button press, I call AudioManager's setSpeakerPhoneOn() to toggle, but it doesn't switch to ear speaker. My audio always blasts through the main speaker.
I tried these solutions (as is apparent in the code below), but none worked:
Switching between earpiece and speakerphone on button
press
Audiomanager Speaker not
working
Here's my code for initializing the AudioManager in onViewCreated:
try {
audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(loudOn);
// loudOn is defined globally, and initialized to false
}
This is the audio playing function which uses AsyncTask:
static private void playCall(final Context context, final String[] contactParts)
{
final MediaPlayer mediaPlayer = new MediaPlayer();
new AsyncTask<Void,Void,Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
try {
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
int audioFile_R_id = //get audio file id
try {
AssetFileDescriptor afd = context.getResources().openRawResourceFd(audioFile_R_id);
if (afd == null) return false;
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build());
} else {
//deprecated in API 26
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
return true;
}
catch (Resources.NotFoundException rnf)
{
rnf.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean prepared) {
if (prepared) {
mediaPlayer.start();
}
}
}.execute();
}
And this is the button code that attempts to toggle:
loudFAB.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
loudOn = !loudOn;
audioManager.setSpeakerphoneOn(loudOn);
}
});
Change the AudioManager
try {
audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(loudOn);
// loudOn is defined globally, and initialized to false
}

SoundPool not playing sound

I am trying to play a sound in my activity using SoundPool but I am unable to hear the sound.
private void beginGame(){
setContentView(R.layout.activity_splash1);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_GAME)
.build();
sp = new SoundPool.Builder()
.setMaxStreams(10)
.setAudioAttributes(aa)
.build();
}else{
sp = new SoundPool(10, AudioManager.STREAM_MUSIC,1);
}
sid = sp.load(Splash1.this,R.raw.bubble,1);
sp.play(sid,1,1,1,0,0.99f);
Thread loading = new Thread() {
public void run() {
try {
sleep(2000);
// TODO NEXT ACTIVITY
}
catch (Exception e) {
e.printStackTrace();
}
finally {
finish();
}
}
};
loading.start();
}
Initially, in a project i worked on, i had a class like [AnswerSound] the one below, so i always get instance of it and call any method as i need. I hope you can look at at and kick of from it.
public class AnswerSound {
private final float volume;
private Context context;
private SoundPool correctAnswerSoundPool;
private int correctAnswerSoundID;
boolean correctLoaded = false;
private SoundPool wrongAnswerSoundPool;
private int wrongAnswerSoundID;
boolean wrongLoaded = false;
public AnswerSound(Context context)
{
this.context = context;
correctAnswerSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 10);
correctAnswerSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener(){
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
correctLoaded = true;
}
}
);
wrongAnswerSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 10);
wrongAnswerSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
wrongLoaded = true;
}
}
);
//assign the sound IDS
correctAnswerSoundID = correctAnswerSoundPool.load(context, R.raw.correct_answer, 1);
wrongAnswerSoundID = wrongAnswerSoundPool.load(context, R.raw.wrong_answer_sound_effect, 2);
//getting the user sound settings
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume / maxVolume;
//then you can play the sound by checking if the sound is loaded
}
public void playCorrectAnswerSound()
{
if (correctLoaded) {
correctAnswerSoundPool.play(correctAnswerSoundID, volume, volume, 1, 0, 1f);
}
}
public void playWrongAnswerSound() {
if (wrongLoaded) {
wrongAnswerSoundPool.play(wrongAnswerSoundID, volume, volume, 1, 0, 1f);
}
}
}

Android - How to remove MediaPlayer loop delays?

I set a music file to loop on MediaPlayer for my game, but it causes a 2 sec delay when it loops.
My code:
boolean activateSounds = getIntent().getBooleanExtra("Activate sounds", true);
if(mp!=null){
mp.reset();
mp.release();
}
mp = MediaPlayer.create(StartGame.this, R.raw.music1);
mp.setVolume(8f, 8f);
mp.setLooping(true); // This is causing delays
if (activateSounds) mp.start();
For a game, this is not interesting. Is there a way to make MediaPlayer run out of loop delays?
I was not able to make setLooping work without a gap.
Only solution that worked for me was to use setNextMediaPlayer call (which is able to start next loop without a gap) and two MediaPlayers.
'pseudo' code:
class Abc implements MediaPlayer.OnCompletionListener {
private final MediaPlayer[] mps = new MediaPlayer[2];
public Abc() {
mps[0] = new MediaPlayer();
mps[1] = new MediaPlayer();
mps[0].setOnCompletionListener(this);
mps[1].setOnCompletionListener(this);
}
public void start()
initMediaPlayer(mps[0]);
initMediaPlayer(mps[1]);
mps[0].setNextMediaPlayer(mps[1]);
mps[0].start();
}
private void initMediaPlayer(MediaPlayer mp)
{
if (mp.isPlaying()){
mp.stop();
}
mp.reset();
final float volume = 0.07f;
mp.setDataSource(MY_SOURCE);
mp.setVolume(volume, volume);
mp.setLooping(false);
try {
mp.prepare();
}catch(Exception error){
Log.d("BackgroundMusic", error.toString());
}
}
#Override
public void onCompletion(MediaPlayer mp)
{
MediaPlayer cur = mps[0] == mp ? mps[1] : mps[0];
initMediaPlayer(mp);
cur.setNextMediaPlayer(mp);
}
}

How to add warning tone after received NFCdate succeed?

I have done an android project on NFC and I want to add a warning tone after receiving NFC date succeed ,how can I do it?
Use SoundPool class. Place your audio files in /res/raw/ and first init loading them (for example in OnCreate Method) and then request to play selected audio file. here is code example:
private SoundPool soundPool;
private boolean tiltSoundsLoaded = false;
private int tiltSoundID;
private int tiltFailureSoundID;
public void initTiltSounds(Context context) {
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
tiltSoundsLoaded = true;
}
});
tiltSoundID = soundPool.load(context, R.raw.swosh_sound_effect, 1);
tiltFailureSoundID = soundPool.load(context, R.raw.fail_metallic, 1);
}
public void playTiltSound(AudioManager audioManager, boolean success) {
try{
int soundToPlay;
if(success)
soundToPlay = tiltSoundID;
else
soundToPlay = tiltFailureSoundID;
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (tiltSoundsLoaded)
soundPool.play(soundToPlay, actualVolume, actualVolume, 1, 0, 1f);
else
Log.e(LOG_TAG, "Tilt Sound not loaded");
}catch(Exception e){
Log.e(LOG_TAG, "Could not play tilt sound");
}
}

Sound not working in ICS

I am using Media player to play a sound file. It is working well on 2.2 and 2.3 but not working for ICS 4.0.3, I have checked that mobile is not on silent mode. my code is:
private MediaPlayer mediaPlayer;
private void playSound(int soundType) {
try {
mediaPlayer = MediaPlayer.create(this, R.raw.beep);
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
Sound in ICS is played like this :
(i copied it from a previous post, so if theres any weird stuff in there i apologize)
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
float lActualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float lMaxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float lVolume = lActualVolume / lMaxVolume;
// Is the sound loaded already?
if (mSoundIsLoaded) {
mSoundPool.play(mSoundID, lVolume, lVolume, 1, 0, 1f);
}
You will have to put the sound file in your assets/raw directory.
edit: I forgot to mention where the mSoundIsLoaded parameter came from. I set it when my sound has been loaded. I do this in my onCreate method. when the sound is loaded I set the boolean field called mSoundIsLoaded. I do this to prevent NullPointerExceptions when playing the sound the loading of the sound looks like this:
mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mSoundIsLoaded = true;
}
});
mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
This is the code i use in my app.. It is working fine in ICS
public void playWelcomeAudio() {
Thread t = new Thread()
{
#Override
public void run() {
AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(R.raw.welcome);
try {
if(afd!=null)
{
UtilLog.d(TAG, "INIT MEDIA PLAYER");
welcomeAudio = new MediaPlayer();
welcomeAudio.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
welcomeAudio.prepare();
welcomeAudio.start();
}
} catch (Exception e) {
UtilLog.e(TAG, "Audio error", e);
}
}
};
t.start();
}
You can remove the thread. It is not necessory.

Categories

Resources