open coding
open coding. 안드로이드 스튜디오 게임효과음 기본/ SoundPool
◀ ▷ ▶ ♤ ♠ ♡ ♥ ♧ ♣ ⊙e
2021. 1. 13. 00:36
반응형
각 버튼 누르면, 각 게임효과음 재생.
package com.www.soundpool;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioAttributes;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//define variables
private Button button1, button2, button3, button4;
private SoundPool soundPool;
private int sound1, sound2, sound3, sound4;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//soundPool initiation
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.build();
soundPool = new SoundPool.Builder()
.setMaxStreams(4)
.setAudioAttributes(audioAttributes)
.build();
//각 sound 설정
sound1 = soundPool.load(this, R.raw.music1,1);
sound2 = soundPool.load(this, R.raw.music2,1);
sound3 = soundPool.load(this, R.raw.music3,1);
sound4 = soundPool.load(this, R.raw.music4,1);
//connec to xml
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
button4 = findViewById(R.id.button4);
//click listener
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
}//finish
//각 버튼 클릭시 각 music playing
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
soundPool.play(sound1,1,1,0,0,1);
break;
case R.id.button2:
soundPool.play(sound2,1,1,0,0,1);
break;
case R.id.button3:
soundPool.play(sound3,1,1,0,0,1);
break;
case R.id.button4:
soundPool.play(sound4,1,1,0,0,1);
break;
}
}//finish
//Ondestory 앱끄면 music도 꺼지게 설정
@Override
protected void onDestroy() {
super.onDestroy();
if(soundPool != null){
soundPool.release();
soundPool = null;
}
}//finish
}