Audio App
Audio App
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"/>
<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:layout_below="@id/playButton"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
//Java File
package com.example.audioplayer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playButton = findViewById(R.id.playButton);
stopButton = findViewById(R.id.stopButton);
// Initialize MediaPlayer
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.prepareAsync(); // Prepare for the next play
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}