我想为我妈妈的生日制作一个应用程序,明天会显示生日快乐消息(已经得到照顾),并在应用程序打开时播放生日快乐歌曲。我是一个完整的Android编程菜鸟,除了基本的xml之外什么都不知道,但我想完成这个。你能不能告诉我在没有用户输入的情况下打开应用程序时用什么代码播放歌曲?
答案 0 :(得分:4)
首先在 res / 目录中创建名为 raw 的文件夹,然后将您的歌曲放入原始文件夹。
在onCreate()
中编写以下代码class song extends Activity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.yoursong);
mediaPlayer.start();
}
@Override
protected void onPause() {
super.onPause();
mediaPlayer.stop();
mediaPlayer.release();
}
}
答案 1 :(得分:1)
Try this
If you want to play song when the app is opened then do following step
step 1. First create the folder named raw in res/ directory.
step 2. Put your birthday song in raw directory in you project.
Then write below code in you activity.
class Playsong extends Activity {
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer= MediaPlayer.create(getApplicationContext(), R.raw.songname);
mPlayer.start();
}
@Override
protected void onPause() {
super.onPause();
mPlayer.stop();
mPlayer.release();
}
}
答案 2 :(得分:0)
首先将歌曲文件放在raw
文件夹下的res
文件夹中。在你的活动之后:
public static MediaPlayer splashSound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
splashSound = MediaPlayer.create(SplashScreen.this, R.raw.start_music);
splashSound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer splashSound) {
splashSound.stop();
splashSound.release();
});