Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何为活动添加声音?(科特林)_Android_Kotlin - Fatal编程技术网

Android 如何为活动添加声音?(科特林)

Android 如何为活动添加声音?(科特林),android,kotlin,Android,Kotlin,我有一个活动,我想有背景音乐运行。我该怎么做呢?首先,您可以创建一个文件夹来保存音频文件。此文件夹的名称为:raw,因此您可以将声音粘贴到该文件夹中,并在启动活动时启动歌曲。例如: 首先,声明变量: var mMediaPlayer: MediaPlayer? = null 现在,您可以启动声音: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)

我有一个活动,我想有背景音乐运行。我该怎么做呢?

首先,您可以创建一个文件夹来保存音频文件。此文件夹的名称为:
raw
,因此您可以将声音粘贴到该文件夹中,并在启动活动时启动歌曲。例如:

首先,声明变量:

var mMediaPlayer: MediaPlayer? = null
现在,您可以启动声音:

override fun onCreate(savedInstanceState: Bundle?) {  
    super.onCreate(savedInstanceState)  
    setContentView(R.layout.activity_main)  
    if (mMediaPlayer == null) { //mMediaPkayer is your variable
      mMediaPlayer = MediaPlayer.create(this, R.raw.water) //raw is the folder where you have the audio files or sounds, water is the audio file (is a example right)
      mMediaPlayer!!.isLooping = true //to repeat again n again
      mMediaPlayer!!.start() //to start the sound
    }else mMediaPlayer!!.start() 
}