programing

버튼 클릭 Android에서 소리 재생

nasanasas 2020. 9. 2. 18:45
반응형

버튼 클릭 Android에서 소리 재생


클릭 할 때 Raw에서 사운드를 재생하는 버튼을 어떻게 얻습니까? 방금 id로 버튼을 button1만들었지 만 내가 작성한 코드가 무엇이든 모두 잘못되었습니다.

import android.media.MediaPlayer;

public class BasicScreenActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);
    }

    Button one = (Button)this.findViewById(R.id.button1);
    MediaPlayer = mp;
    mp = MediaPlayer.create(this, R.raw.soho);
    zero.setOnCliclListener(new View.OnClickListener() )

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



}

이것은 원본 게시물에 제공된 코드에서 가장 중요한 부분입니다.

Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        mp.start();
    }
});

단계별로 설명하려면 :

Button one = (Button) this.findViewById(R.id.button1);

첫 번째는 사운드 재생에 사용되는 버튼의 초기화입니다. Activity의을 사용하여 findViewById할당 한 Id (이 예제의 경우 :)를 전달하여 R.id.button1필요한 버튼을 가져옵니다. 초기화 Button하는 변수에 쉽게 할당 할 수 있도록 캐스트합니다 one. 이것이 어떻게 작동하는지 더 설명하는 것은이 답변의 범위를 벗어납니다. 이것은 작동 방식에 대한 간략한 통찰력을 제공합니다.

final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);

이것은 MediaPlayer. MediaPlayer는 Static Factory 메서드 디자인 패턴을 따릅니다 . 인스턴스를 가져 오려면 해당 create()메서드를 호출하고 재생하려는 사운드의 컨텍스트와 리소스 ID (이 경우)를 전달 R.raw.soho합니다. 우리는 그것을 final. Jon Skeet는 우리가 여기서 그렇게하는 이유에 대해 훌륭한 설명을 제공했습니다 .

one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        //code
    }
});

마지막으로 이전에 초기화 된 버튼이 수행 할 작업을 설정합니다. 버튼 클릭시 소리 재생! 이를 위해 OnClickListener버튼을 설정 합니다 one. 내부는 단지 하나의 방법이며, onClick()무엇을해야하는지 지시 버튼이 들어 클릭에를 .

public void onClick(View v) {
    mp.start();
}

사운드를 재생하기 위해 MediaPlayer의 start()메서드를 호출 합니다. 이 메서드는 사운드 재생을 시작합니다.

이제 Android에서 버튼 클릭시 소리를 재생할 수 있습니다!


보너스 부분 :

아래 댓글에서 언급했듯이 감사합니다 Langusten Gustel! Android 개발자 참조에서 권장release() 하는대로 더 이상 사용되지 않을 리소스를 확보하기 위해 메서드를 호출하는 것이 중요합니다 . 일반적으로 이것은 재생할 사운드가 재생을 완료하면 수행됩니다. 이를 위해, 우리는 추가 OnCompletionListener우리에게 mp 이렇게 같은 :

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        //code
    }
});

onCompletion메서드 내에서 다음 과 같이 릴리스합니다 .

public void onCompletion(MediaPlayer mp) {
    mp.release();
}

이것을 구현하는 더 나은 방법 이 분명히 있습니다 . 예를 들어 MediaPlayer를 클래스 변수로 만들고 이를 사용 하는 Fragment또는 Activity사용 하는 수명주기와 함께 수명주기를 처리 할 수 있습니다. 그러나 이것은 다른 질문에 대한 주제입니다. 이 답변의 범위를 작게 유지하기 위해 Android에서 버튼 클릭시 소리를 재생하는 방법을 설명하기 위해 작성했습니다 .


원본 게시물

먼저. 문을 블록 안에 넣어야하며,이 경우에는 onCreate 메서드를 사용해야합니다.

둘째. 버튼을 변수 1 로 초기화 다음 변수 0 을 사용하고 onClickListener를 불완전한 onClickListener로 설정했습니다. setOnClickListener에 변수 1사용하십시오 .

셋째, onClick 내부에 사운드를 재생하는 로직을 넣습니다.

요약해서 말하자면:

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BasicScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);

        Button one = (Button)this.findViewById(R.id.button1);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
        one.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

100 % 테스트 및 작동

public class MainActivity extends ActionBarActivity {
    Context context = this;
    MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        mp = MediaPlayer.create(context, R.raw.sound);
        final Button b = (Button) findViewById(R.id.Button);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                        mp = MediaPlayer.create(context, R.raw.sound);
                    } mp.start();
                } catch(Exception e) { e.printStackTrace(); }
            }
        });
    }
}

이게 우리가해야 할 전부 였어

if (mp.isPlaying()) {
    mp.stop();
    mp.release();
    mp = MediaPlayer.create(context, R.raw.sound);
}

이 작업을 수행하는 가장 좋은 방법은 LogCat에서 한 문제를 차례로 검색 한 후 찾은 것입니다.

MediaPlayer mp;
mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        mp.reset();
        mp.release();
        mp=null;
    }
});
mp.start();

미디어 플레이어를 릴리스 하지 않으면 LogCat에서 다음 오류가 발생합니다.

Android : MediaPlayer가 출시되지 않고 종료 됨

미디어 플레이어를 재설정 하지 않으면 LogCat에서 다음 오류가 발생합니다.

Android: mediaplayer went away with unhandled events

따라서 안전하고 간단한 코드를 재생하여 미디어 플레이어를 사용하십시오.

동일한 활동 / 조각에서 둘 이상의 사운드를 재생하려면 다음과 같은 새 미디어 플레이어를 만드는 동안 resID를 변경하기 만하면됩니다.

mp = MediaPlayer.create(context, R.raw.sound_two);

그리고 그것을 재생하십시오!

즐기세요!


import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer mp;
    Button one;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mp = MediaPlayer.create(this, R.raw.soho);
        one = (Button)this.findViewById(R.id.button1);

        one.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.start();
            }
        });
    }
}

  • 오디오는 raw폴더 에 있어야합니다 . 존재하지 않는 경우 새로 만듭니다.
  • 원시 폴더는 res 폴더 내에 있어야합니다.
  • The name mustn't have any - or special characters in it.

On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

Example:

private Button myButton;
private MediaPlayer mp;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);
        mp = MediaPlayer.create(this, R.raw.gunshot);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
}
}

Button button1=(Button)findViewById(R.id.btnB1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MediaPlayer mp1 = MediaPlayer.create(this, R.raw.b1);
mp1.start();
}
});

Try this i think it will work


there are some predefined sounds: SHUTTER_CLICK, FOCUS_COMPLETE, START_VIDEO_RECORDING, STOP_VIDEO_RECORDING.

Nice!

MediaActionSound

A class for producing sounds that match those produced by various actions taken by the media and camera APIs. Docs

use like:

fun playBeepSound() {
    val sound = MediaActionSound()
    sound.play(MediaActionSound.START_VIDEO_RECORDING)
}

public class MainActivity extends AppCompatActivity {

    public void clickMe (View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
        mp.start();

    }

create a button with a method could be called when the button pressed (onCreate),

then create a variable for (MediaPlayer) class with the path of your file

MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);

finally run start method in that class

mp.start();

the file will run when the button pressed, hope this was helpful!


Instead of resetting it as proposed by DeathRs:

if (mp.isPlaying()) {
       mp.stop();
       mp.release();
       mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();

we can just reset the MediaPlayer to it's begin using:

if (mp.isPlaying()) {
       mp.seekTo(0)
}

All these solutions "sound" nice and reasonable but there is one big downside. What happens if your customer downloads your application and repeatedly presses your button?

Your MediaPlayer will sometimes fail to play your sound if you click the button to many times.

I ran into this performance problem with the MediaPlayer class a few days ago.

Is the MediaPlayer class save to use? Not always. If you have short sounds it is better to use the SoundPool class.

A save and efficient solution is the SoundPool class which offers great features and increases the performance of you application.

SoundPool is not as easy to use as the MediaPlayer class but has some great benefits when it comes to performance and reliability.

Follow this link and learn how to use the SoundPool class in you application:

Save Solution

참고URL : https://stackoverflow.com/questions/18459122/play-sound-on-button-click-android

반응형