Android游戏设计之-------游戏音效的播放 SoundPool

在res文件夹中新建raw文件夹,然后从LOL中复制了一个音效mp3文件到raw中。命名为sound1.mp3


在layout上画两个按钮,一个用来播放音效,一个用来停止音效!


package com.example.sample2_1_soundpool;

import java.util.HashMap;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	SoundPool soundPool;
	HashMap<Integer,Integer> hashMap;
	
	int currentStreamId; //当前正在播放的streamid
	

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initSoundPool();
        
        Button button1=(Button)this.findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				PlaySound(1,0);
				
				Toast.makeText(getBaseContext(), "即时播放音效", Toast.LENGTH_LONG)
				.show();
			}
        	
        });
        
        Button button2=(Button)this.findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				soundPool.stop(currentStreamId);
				
				Toast.makeText(getBaseContext(), "停止播放音效", Toast.LENGTH_LONG)
				.show();
			}
        	
        });
        
    }


    protected void PlaySound(int sound, int loop) {
		// TODO Auto-generated method stub
		AudioManager audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
		
		float streamVolumeCurrent = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		
		float streamVolumeMax=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		
		float volume=streamVolumeCurrent/streamVolumeMax;
		
		currentStreamId=soundPool.play(hashMap.get(sound), volume, volume, 1, loop, 1.0f);
		
	}


	private void initSoundPool() {
		// TODO Auto-generated method stub
		soundPool=new SoundPool(4,AudioManager.STREAM_MUSIC,0);
		hashMap=new HashMap<Integer,Integer>();
		
		hashMap.put(1, soundPool.load(this,R.raw.sound1,1)); //加载sound1并设置为1号声音
		
		
	}


	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


工程打包:

http://download.csdn.net/detail/cp790621656/6321929





你可能感兴趣的:(游戏,android)