Streaming audio file to soundpool load() Android - android

I want to use SoundPool class to create Playback speed effects. To play sound fastly or slowly (1x,0.5x,2x etc).
But the problem is soundpool handles only small files. When i give a large file. It doesn't play anything.
I was wondering if it would be possible to load stream of music (some bytes of my large audio file) and play it via soundpool. any idea.??
Here is my code for soundPool to play song
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
soundID = soundPool.load(Environment.getExternalStorageDirectory()+"/cm.mp3", 1);
soundPool.play(soundID, volume, volume, 1, 0, 1.0f);
I found JetPlayer and AudioTrack classes, but i m not finding any good tutorials to handle this.

You will need to check file is loaded successfully before playing it using SoundPool.setOnLoadCompleteListener
public void loadSound (String strSound, int stream) {
boolean loaded = false;
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
try {
stream= mSoundPool.load(aMan.openFd(strSound), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Is the sound loaded already?
if (loaded) {
mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
}
}
where aMan is
AssetFileDescriptor aMan = getAssets();

Related

how can i set mediaPlayer speed for api less then 23

player.setPlaybackParams(player.getPlaybackParams().setSpeed(0.5f));
this requires an api call 23
iam trying to use SoundPool but it is not so efficent as of MediaPlayer Is any alternate to SoundPool for audioPlaying
final float playbackSpeed=1.5f;
final SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
final String path=Environment.getExternalStorageDirectory().getAbsolutePath() + "/folioreader/audio"+".mp3";
final int soundId = soundPool.load(path, 1);
AudioManager mgr = (AudioManager) mHalfSpeed.getContext().getSystemService(Context.AUDIO_SERVICE);
final float volume = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener()
{
#Override
public void onLoadComplete(SoundPool arg0, int arg1, int arg2)
{
soundPool.play(soundId, volume, volume, 1, 0, playbackSpeed);
}
});
soundPool.pause(soundId)
Use media codec class. This class can decode it and you can use Audio Track on decoded data to render (play) it. But you need to skip the samples as per your speed requirement to play in the particular speed. This approach should work. Refer mediacodec and audiotrack in android developer resources.

android sound pool not appear

I want to add a sound effect when a user clicks on a button.
I tried this:
case R.id.b_all_addresses_addAddress:
// Getting the user sound settings
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)
soundPool.play(soundID, volume, volume, 1, 1, 1f);
else
Toast.makeText(this, "could I hate you God more?", Toast.LENGTH_SHORT).show();
in my on create I did this:
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(10, 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.thip, 1);
the sound is just 6 KB.
My Problem
I can't hear the voice
what values are you getting back for volume?
They should be between 0.1 and 0.99. Try using 0.5 as a hard-coded setting and see whether that works. I vaguely remember someone here once reported a "bug" in SoundPool which meant that 0 and 1 meant "mute" and your volume had to be between these two values in order to be heard.
Also: What format is your sound in? not all phones can play all the formats. Some need ogg, some are fine with WAV.
This here works for me on HTC Sensation XE, Android 4.03:
*WAV
*2 Channels
*16 bit PCM
*44.1kHz

Soundpool plays only first 5 secs of file. Why?

I use Soundpool in my app, so far it works good, but I do have a wav file which is 10 secs. Unfortunately, soundpool plays only the first 5 secs. How to make soundpool to play the whole track? I have converted wav to -- ogg and mp3 still the same issue. It plays only the first 5 secs. Any help would be much appreciated.
//set up audio player
mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
//load fx
mSoundPoolMap.put(RAW_1_1, mSoundPool.load(this, R.raw.loop1, 1));
//playing soundpool
case R.id.button1:
mSoundPool.stop(mStream1);
mStream1= mSoundPool.play(mSoundPoolMap.get(RAW_1_1), streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
UPD Last: Maybe someone will find it here and read it. Seems soundpool cant play more then 5 secs. It is his maximum, for more longer sounds use MediaPlayer. I hope you will not spend so much of your time like i did)
So I think you reached the 1M limit in SoundPool.
SoundPool is hard code the buffer size as 1M, for all loaded file, store in pcm format.
So it do not care of ogg or wav.
We have solved similar problem by decreasing in our *.ogg effects sample rate. Our initial sample rate was 44 kHz ~ and only 10 sec of sound played, decreasing to 16 kHz increase playability to 30 seconds
Solution was found in this discussion
SoundPool designed to play short sound effects. To play music (big audio files) you need to use MediaPlayer
// R.raw.audio_file - res/raw/audio_file.mp3
mediaPlayer = MediaPlayer.create(this, R.raw.audio_file);
mediaPlayer.start();
This activity is works for me
public class MainActivity extends Activity {
private Integer soundID;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
// Load the sound
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
final float volume = actualVolume / maxVolume;
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
try {
Thread.sleep(5000); // play twice
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
});
}
});
soundID = soundPool.load(this, R.raw.sound2, 1);
//load fx
//playing soundpool
}
}
You must load you sound asynchrony and check audio cache - it can be overflow.
Read this article
http://www.google.by/url?http://www.vogella.com/articles/AndroidMedia/article.html
Its very heedful
Your file is probably too large. Try to change from stereo to mono, if you do not need stereo anyway.
Or try to downsample your file.
Reducing the filesice worked in my case.

Soundpool sample not ready

I have a .wav file that I'd like to use across my game, currently I am loading the sound in onCreate() of each activity in the game.
soundCount = soundpool.load(this,R.raw.count, 1);
The sound will be played once the activity starts.
soundpool.play(soundCount, 0.9f, 0.9f, 1, -1, 1f);
Problem is at times I will hit the error "sample x not ready".
Is it possible to load the .wav file once upon starting the game and keep it in memory and use it later across the game? Or is it possible to wait for 1-2 seconds for the sound to load finish?
You'll need to wait for it to finish by adding a listener via SoundPool.setOnLoadCompleteListener.
Since my project is compatible with Android 1.5 and I couldn't use setOnLoadCompleteListener, I resolved making the play of sound delayed.
My source code follows:
playSound_Delayed(soundId, 100);
// (..)
private void playSound_Delayed (final int soundId, final long millisec) {
// TIMER
final Handler mHandler = new Handler();
final Runnable mDelayedTimeTask = new Runnable() {
int counter = 0;
public void run() {
counter++;
if (counter == 1) {
boolean ret = mHandler.postDelayed(this, millisec);
if (ret==false) Log.w("playSound_Delayed", "mHandler.postAtTime FAILED!");
} else {
playSound(soundId);
}
}
};
mDelayedTimeTask.run();
}
you should use setOnLoadCompleteListener if possible ... if not, wrap a while loop around your call to 'play'. something like:
int waitLimit = 1000;
int waitCounter = 0;
int throttle = 10;
while(soundPool.play(soundId, 1.f, 1.f, 1, 0, 1.f) == 0 && waitCounter < waitLimit)
{waitCounter++; SystemClock.sleep(throttle);}
this will retry 'play' 1000 times on a 10ms interval. this should be run on a non-ui thread of course, and is still not ideal. but maybe a little stronger than waiting an arbitrary time and expecting the pool to be ready.
The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream which we simply can call preparation of Stream, that takes some times depending on size of sound file. And if we try to play the sound before that process is over, we get "sample x not ready" error.
There are two solutions for this
implement setOnLoadCompleteListener or
wait arbitrary amount of time so that preparation is over
and then play it
Note that there is no exception for this condition or application is not crashing without any try-catch
private SoundPool soundPool;
private int my_sound;
boolean loaded = false;
// In the constructor
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
my_sound = soundPool.load(this, R.raw.blast_sound, 1);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
loaded = true;
}
});
// then where ever you want to play the sound, type
if (loaded) {
soundPool.play(my_sound, 0.9f, 0.9f, 1, 0, 1f);
}
I solved with problem with simple do-while cicle. The method play() return non-zero streamID if successful, zero if failed. So, it's sufficient to check the return value.
int streamID = -1;
do {
streamID = soundPool.play(soundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
} while(streamID==0);
This would work for you definitely !
public void playWavFile() {
Thread streamThread = new Thread(new Runnable() {
#Override
public void run() {
SoundPool soundPool;
final int wav;
String path = "/mnt/sdcard/AudioRecorder/record.wav";
soundPool = new SoundPool(5,AudioManager.STREAM_MUSIC, 0);
wav = soundPool.load(path, 1);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// TODO Auto-generated method stub
soundPool.play(wav,100, 100, 0, 0, 1f);
}
});
}
});
streamThread.start();
}
This sounds crazy, but don't play sounds right away. Give your app a couple of seconds to initialize the SoundPool. In my app, this was exactly the issue; I added a fake "loading" screen of ~3 seconds, and then everything worked. (I didn't even need to preload the sounds.)

Error when playing Media Files

I'm using MediaPlayer to play some sounds files, which at times overlap. I notice that in the LogCat window I keep getting this message:
android max instances of component OMX.TI.ACC. Decode already created.
It seems to have no effect on my application as the sounds continue to play just fine. Does anyone know what this message means, and do I need to worry about it?
SoundPool may be a better option for playing multiple, short sounds.
Creating SoundPool
public static final int SOUND_1 = 1;
public static final int SOUND_2 = 2;
SoundPool mSoundPool;
HashMap<Integer, Integer> mHashMap;
#Override
public void onCreate(Bundle savedInstanceState){
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100);
mSoundMap = new HashMap<Integer, Integer>();
if(mSoundPool != null){
mSoundMap.put(SOUND_1, mSoundPool.load(this, R.raw.sound1, 1));
mSoundMap.put(SOUND_2, mSoundPool.load(this, R.raw.sound2, 1));
}
}
Then play a sound by calling a custom function.
Playing Sound
/*
*Call this function from code with the sound you want e.g. playSound(SOUND_1);
*/
public void playSound(int sound) {
AudioManager mgr = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;
if(mSoundPool != null){
mSoundPool.play(mSoundMap.get(sound), volume, volume, 1, 0, 1.0f);
}
}

Categories

Resources