Programming
2014年5月1日 星期四
Android -- Playing Sound File
Android -- Playing Sound File
A simple example is given as below.
1. First of all, prepare a sound file (prefer a MP3 format to save the space).
2. Second, create a folder 'raw' in the res (i.e. res/raw).
3. Third, declare the MediaPlayer mp under the main class.
public class MainActivity extends Activity {
private MediaPlayer mp;
4. On the main program, type this under the onCreate section:
mp = MediaPlayer.create(this, R.raw.yourmp3file);
Example:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/// sound ////
mp = MediaPlayer.create(this, R.raw.yourmp3file);
5. Use this code to play the sound:
mp.start();
6. Finish.
Remark:
In case, there are so many sound files, use the following code to avoid using too much memory that may create crash.
public void onDestroy() {
super.onDestroy();
if(mp != null)
{
mp.stop();
mp.release();
}
}
:)
訂閱:
文章 (Atom)