The music either doesn't even start playing sometimes, but when it does, it stops after a few seconds. The file is 2 minutes long. I really don't know what's the problem.
#Override
public void onCreate(Bundle savedInstanceState) {
music = soundPoolVar.load(this, R.raw.music11, 1);
}
then
public void soundPlay(int i, MySurface pl, float volume) {
if (soundOn == true) {
switch (i) {
case 11:
soundPoolVar.play(music, 1, 1, 0, 0, 1);
break;
}}}
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();
Related
I have been integrating the YoutubePlayer API for with my Android project. The videos from the playlist are working well. What I am trying to do is have the audio start low and fade in over 30seconds.
What I have done so far, for some reason is doing somthing really weird. It set it to max volume and if you try to turn it down it turns it back up again really straight away.
The way I thought I could do it was to set the audio manager to a 0 volume and then on an ontick timer raise that by 1 until it got to the max volume.
The code below was my attempt, but like I said it is doing weird things.
Thanks for your help
youTubePlayer.loadPlaylist(playListTitle);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Add listeners to YouTubePlayer instance
youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onLoaded(String arg0) {
youTubePlayer.play();
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
Integer volumeRaisingTime = 30000;
new CountDownTimer(volumeRaisingTime, 1000) {
Integer deviceMaxVolume = 20;
Integer devicevolume = 0;
public void onTick(long millisUntilFinished) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 20, 0);
if (devicevolume > deviceMaxVolume){
devicevolume++;
Log.d("Device Volume:", ""+devicevolume);
}
}
public void onFinish() {
}
}.start();
}
I have several GridView items that play a small .ogg file when they are selected. They are played using the SoundPool class, however this class seems very intermittent - sometimes the sound plays, sometimes it doesn't; there is no pattern to this so I am having trouble figuring out why it's doing it.
Here is my code:
public void playSelectionSound(){
SoundPool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
int soundId = sp.load(this, R.raw.char_select, 1);
sp.play(soundId, 1, 1, 0, 0, 1);
}
I eventually resorted to switching to MediaPlayer instead of SoundPool:
MediaPlayer mp = MediaPlayer.create(this, R.raw.char_select); //open media player
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start(); //play the sound
Works everytime.
You shouldn't try to play it immediately after the load since the load can take time. Instead, you should use SoundPool.OnLoadCompleteListener() and play it in that callback. Here you can be sure that soundpool has loaded successfully.
I need to have the same short wav file (1 second) play each time the user presses a single button. I have the following code that works for about 30 clicks and then the app "Force closes" on the device. I think what is going on is that new instances of media player are being created and then the instances build up (approx 30 clicks) and the app crashes. So I then added the "release" instance in the hope that on button-click the wav would play and then the mediaplayer would be released. However, it doesnt work that way. With the mp.release() no sound is played possibly becaue the medaiplayer gets released too soon for the user to hear the sound?
Anyone have a good tip to help me getting this to work? Thank you all so much.
Button button2 = (Button) findViewById(R.id.button10);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
mp.start();
mp.release();
Its simple just create the MediaPlayer once, and play it over time.
private MediaPlayer mp;
public void onClick(View v) {
// Perform action on click
if (mp == null){
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
}
mp.start();
}
Why use MediaPlayer, when SoundPool is better suited for small audio files? As a base you could use this:
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 70);
final HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();
final int soundID = 4;
soundPoolMap.put(soundID, soundPool.load(this, R.raw.wav_sound, 4));
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
{
public void onLoadComplete(SoundPool soundPool, int sampleId, int status)
{
if (sampleId == 4)
{
soundPool.play(4, 50, 50, 1, 0, 1f);
}
}
});
Here is the simple solution that will work
MediaPlayer mp;
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
public void onClick(View v) {
// Perform action on click
if(mp.isPlaying())
{
mp.stop();
mp.reset();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.clicker);
mp.start();
This is will check if mediaplayer is already playing..If it already playing it will stop and release it and then initialize that mediaplayer(mp) object and start the mediaplayer.
If it is not playing it will execute the code after the if statement and the start the media player after initialzing the mediaplayer object(mp in this case)
To learn more about MediaPlayer study this http://developer.android.com/reference/android/media/MediaPlayer.html. Study the Mediaplayer life cycle
I have a small (200kb) mp3 in the res/raw folder of my android app. I am trying to run it in an emulator from Eclipse. It is recognized as a resource in the R file but when I try to prepare/start, my activity crashes! Was there something else I needed to change, perhaps in the manifest?
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
try {
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
// handle this later
}
When starting the activity i.e on onCreate put the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
mPlayer.start();
}
When stopping the activity i.e on onDestroy put the following code.
public void onDestroy() {
mPlayer.stop();
super.onDestroy();
}
Hope it helps :)
You'll likely prefer to use the SoundPool class. It reduces latency when it's time to play the sound, and offers other niceties like being able to prioritise sounds when there are too many to play at once.
From the docs:
A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback.
For example:
/**
* How many sounds can be played at once.
*/
private static final int MAX_SOUND_POOL_STREAMS = 4;
/**
* Modify this as part of your own priority scheme. Higher numbers mean higher
* priority. If you don't care, it's okay to use the same priority for every
* sound.
*/
private static final int NORMAL_PRIORITY = 10;
private int mySoundId;
#Override
public void setupContent() {
this.soundPool = new SoundPool(MAX_SOUND_POOL_STREAMS,
AudioManager.STREAM_MUSIC, 100);
this.mySoundId = this.soundPool.load(this.getApplicationContext(),
R.raw.mySound, 1);
}
#Override
private void playMySound() {
this.soundPool.play(this.mySoundId, 1, 1, NORMAL_PRIORITY, 0, 1);
}
this is a static method I use in my projects.
I add it to my Utils class:
public static void playSound(final Context context, final SoundType type)
{
new Thread(new Runnable()
{
#Override
public void run()
{
MediaPlayer mediaPlayer = new MediaPlayer();
int resId = -1;
switch (type)
{
case INCOMING_NOTIFICATION:
resId=R.raw.noti_sound;
break;
case SEND_BETTING_SLIP:
resId=R.raw.slip_sent;
break;
case TRIVIA_RIGHT_ANSWER:
resId=R.raw.game_bonus;
break;
case TRIVIA_WRONG_ANSWER:
resId=R.raw.whistle_referee_trivia_bad_answer;
break;
}
if (resId != -1)
{
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(false);
mediaPlayer.start();
while (mediaPlayer.isPlaying() == true)
{
}
}
}
}).start();
}
}
now I defind an Enum (SoundType) and placed the mp3 files in raw folder under
res folder.
How do I set up an audiofile to play when a user touches an image.
Where should I store the audio file and what code should I use to actually play the file?
I don't want to bring up the MediaPlayer interface or anything like that.
I was thinking of doing it like this:
foo = (ImageView)this.findViewById(R.id.foo);
foo.setOnClickListener(this);
public void onClick(View v) {
if (foo.isTouched()) {
playAudioFile();
}
}
Thanks
This won't create a bring up the MediaPlayer interface... it will just play the sound you want.
Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);
mp.start();
}
});
In this case, R.raw.slayer represents an audio file called slayer.mp3 that is stored in the res/raw/ folder and once you click the button the droid will rock you...
You can also achieve the same using SoundPool.
MediaPlayer first loads the whole sound data in memory then play, so it produces some lag when we switch among sounds frequently.
SoundPool is a better option with small size sound file and produces better result with .ogg media file.
SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
// 5 indicates the maximum number of simultaneous streams for this SoundPool object
pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// The onLoadComplet method is called when a sound has completed loading.
soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
// second and third parameters indicates left and right value (range = 0.0 to 1.0)
}
});
Button btn = findViewById(R.id.boton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sound = pl.load(this, R.raw.sound_01, 0);
}
});
public void aud_play(View view) {
if (!mp.isPlaying()) { //If media player is not playing it.
mp = MediaPlayer.create(this, R.raw.audio_name);
mp.start();
} else {// Toast of Already playing ...
}
}