Im making an app, and i want it to make a sound when a activity is opened , the sound file is in R.raw.sound_file , if someone could do some example code to make my app play a sound that would be great :)
+1
A:
doesn't the android.media.MediaPlayer
class do this?
Reference: http://developer.android.com/reference/android/media/MediaPlayer.html
Example: http://developer.android.com/guide/topics/media/index.html
Step 2 of the example says:
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1);
mp.start();
In your case, I'd use the onStart()
inside your Activity class:
public class MyActivity extends Activity {
...
protected void onStart() {
super.onStart();
MediaPlayer mp = MediaPlayer.create(this, R.raw.sound_file_1);
mp.start();
}
...
}
ayman
2010-03-16 23:29:18
i dont know what to put as the context , ive tried putting it as null but the app just force closes
Dan
2010-03-17 07:05:14
The context should be your Activity (or Service, BroadcastReceiver, ...) from which you call this.But in your case: When you want to play the sound when the application first launches, you could start the MediaPlayer (as described above) from Application.onCreate(), this way I suspect the audio to be played earlier. But do not, this will play the audio always, also if another task starts one of your other Activities (if this is possible).
MrSnowflake
2010-03-17 09:16:47
Ok , so what code do i use if i want to do the .onCreate() method ...
Dan
2010-03-17 16:45:58
As MrSnowflake points out, the Activity class itself extends Context: http://developer.android.com/reference/android/app/Activity.html have you tried passing that in? The doc page for Context lists all direct and indirect subclasses: http://developer.android.com/reference/android/content/Context.html
ayman
2010-03-19 21:22:43
I updated the solution to show how to do this in your Activity onStart() method.
ayman
2010-03-23 21:07:09