2swan
음악 듣기 예제 본문
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="음악듣기"
android:textSize="30sp"/>
<SeekBar
android:id="@+id/pbMP3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
main.activity
//오디오 음악듣기
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar pbMp3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch switch1 = findViewById(R.id.switch1);
pbMp3 = findViewById(R.id.pbMP3);
pbMp3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
mediaPlayer.seekTo(i);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
switch1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(switch1.isChecked() == true){
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.song1);
mediaPlayer.start();
makeThread();
}else{
mediaPlayer.stop();
}
}
});
}
void makeThread(){
new Thread(){
@Override
public void run() {
//음악이 계속 작동중이라면
while (mediaPlayer.isPlaying()){
pbMp3.setMax(mediaPlayer.getDuration());
//현재 위치 지정
pbMp3.setProgress(mediaPlayer.getCurrentPosition());
SystemClock.sleep(100);
}
pbMp3.setProgress(0);
}
}.start();
}
}
결과 값
- 스위치 on 하면 processbar가 흘러간다.
'Programming > Android Example' 카테고리의 다른 글
Retrofit 예제 (0) | 2023.08.09 |
---|---|
Progressbar (0) | 2023.08.09 |
Tab 예제 (0) | 2023.08.09 |
슬라이드 예제 2 (0) | 2023.08.09 |
가로(세로) 슬라이드 (0) | 2023.08.09 |