Reputation: 11
I am having trouble with audio in Android. Here is the deal, I have a very simple splash screen. My intention is once the screen loads it will play a very small audio file.
The problem is that a lot of the time, the audio will play before the splash screen actually appears.
Is there a way programmatically to verify that the screen has loaded? I do not want to add an unnecessary timer to make sure the sound doesn't play before it loads. And I want the sound to play at the exact moment the screen appears.
Here is a snippet from my xml file:
<ImageView
android:src="@drawable/splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
splash is a .png image
And here is the onCreate code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scarysplash);
mpPlaySound = MediaPlayer.create(this, R.raw.scream1);
mpPlaySound.start();
}
}
Thanks in advance for your help!
Upvotes: 1
Views: 593
Reputation: 6268
you are not the only only one who has similar problem:)) There are couple of ways how to do that, the popular one is to implement OnGlobalLayoutListener(), e.g.:
View yourView = ...;
yourView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener()
{
// -----------------------------------------
//
// Callback method to be invoked when the
// global layout state or the visibility
// of views within the view tree changes
//
// -----------------------------------------
@Override
public void onGlobalLayout()
{
// Remove view
View yourView = findViewById( R.id.yourId );
if ( yourView != null )
{
yourView .getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// PLAY SOUND
}
});
Petr
Upvotes: 2