标签:
1 package com.example.day18_05gameaudiodemo; 2 3 import java.io.IOException; 4 5 import android.app.Activity; 6 import android.media.AudioManager; 7 import android.media.MediaPlayer; 8 import android.media.SoundPool; 9 import android.os.Bundle; 10 import android.os.Environment; 11 import android.view.Menu; 12 import android.view.MenuItem; 13 import android.view.View; 14 import android.view.View.OnClickListener; 15 import android.widget.Button; 16 17 public class MainActivity extends Activity implements OnClickListener { 18 19 private SoundPool sp; 20 private int sound1; 21 private int sound2; 22 private int sound3; 23 private MediaPlayer mediaPlayer; 24 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 super.onCreate(savedInstanceState); 28 setContentView(R.layout.activity_main); 29 30 Button bt_gb = (Button) findViewById(R.id.bt_bg); 31 Button bt_shoot1 = (Button) findViewById(R.id.bt_shoot1); 32 Button bt_shoot2 = (Button) findViewById(R.id.bt_shoot2); 33 Button bt_shoot3 = (Button) findViewById(R.id.bt_shoot3); 34 35 36 bt_gb.setOnClickListener(this); 37 bt_shoot1.setOnClickListener(this); 38 bt_shoot2.setOnClickListener(this); 39 bt_shoot3.setOnClickListener(this); 40 41 42 sp = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); 43 sound1 = sp.load(this, R.raw.shoot1, 1); 44 sound2 = sp.load(this, R.raw.shoot2, 1); 45 sound3 = sp.load(this, R.raw.shoot3, 1); 46 47 mediaPlayer = new MediaPlayer(); 48 mediaPlayer.reset(); 49 try { 50 mediaPlayer.setDataSource(Environment.getExternalStorageDirectory() 51 .getAbsolutePath() + "/bgmusic.mp3"); 52 mediaPlayer.prepare(); 53 } catch ( Exception e) { 54 // TODO Auto-generated catch block 55 e.printStackTrace(); 56 } 57 58 } 59 60 @Override 61 public void onClick(View v) { 62 // TODO Auto-generated method stub 63 switch (v.getId()) { 64 case R.id.bt_bg: 65 if (mediaPlayer!=null) { 66 mediaPlayer.start(); 67 } 68 break; 69 case R.id.bt_shoot1: 70 sp.play(sound1, 1, 1, 0, 0, 1); 71 break; 72 case R.id.bt_shoot2: 73 sp.play(sound2, 1, 1, 0, 0, 1); 74 75 break; 76 case R.id.bt_shoot3: 77 sp.play(sound3, 1, 1, 0, 0, 1); 78 79 break; 80 default: 81 break; 82 } 83 } 84 85 86 87 88 }
标签:
原文地址:http://www.cnblogs.com/woodrow2015/p/4542662.html