Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเล่นเสียง Ringtone/Alarm/Notification ใน Android

ภาพรวม

Android มีเสียงระบบ (System Sounds) 3 ประเภทหลัก: Ringtone (โทรเข้า), Notification (แจ้งเตือน), Alarm (นาฬิกาปลุก) สามารถเข้าถึงและเล่นได้ผ่าน RingtoneManager และ MediaPlayer

ตัวอย่าง: เล่นเสียงแต่ละประเภทแยกกัน

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → New Project → Empty Activity (Package: app.tutorialspoint.com.notifyme)

ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:id="@+id/btnPlayNotification"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:text="Play Notification Sound" />

        <Button
            android:id="@+id/btnPlayRingtone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:text="Play Ringtone" />

        <Button
            android:id="@+id/btnPlayAlarm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:text="Play Alarm Sound" />

        <Button
            android:id="@+id/btnStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Stop All Sounds"
            android:backgroundTint="#F44336"
            android:textColor="#FFFFFF" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

ขั้นตอนที่ 3: MainActivity.java

package app.tutorialspoint.com.notifyme;

import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;

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

        Button btnPlayNotification = findViewById(R.id.btnPlayNotification);
        Button btnPlayRingtone = findViewById(R.id.btnPlayRingtone);
        Button btnPlayAlarm = findViewById(R.id.btnPlayAlarm);
        Button btnStop = findViewById(R.id.btnStop);

        btnPlayNotification.setOnClickListener(v -> playSound(RingtoneManager.TYPE_NOTIFICATION));
        btnPlayRingtone.setOnClickListener(v -> playSound(RingtoneManager.TYPE_RINGTONE));
        btnPlayAlarm.setOnClickListener(v -> playSound(RingtoneManager.TYPE_ALARM));
        btnStop.setOnClickListener(v -> stopSound());
    }

    private void playSound(int type) {
        stopSound(); // หยุดเสียงเก่าก่อน

        try {
            // ดึง URI ของเสียงระบบตามประเภท
            Uri soundUri = RingtoneManager.getDefaultUri(type);
            if (soundUri == null) {
                // Fallback: ใช้เสียง Notification ถ้าไม่มีเสียงประเภทนั้น
                soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(this, soundUri);
            mediaPlayer.setAudioAttributes(new android.media.AudioAttributes.Builder()
                    .setUsage(getAudioUsage(type))
                    .setContentType(android.media.AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build());
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(mp -> stopSound());
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private int getAudioUsage(int ringtoneType) {
        switch (ringtoneType) {
            case RingtoneManager.TYPE_RINGTONE:
                return android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE;
            case RingtoneManager.TYPE_ALARM:
                return android.media.AudioAttributes.USAGE_ALARM;
            case RingtoneManager.TYPE_NOTIFICATION:
            default:
                return android.media.AudioAttributes.USAGE_NOTIFICATION;
        }
    }

    private void stopSound() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopSound();
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>
</manifest>

RingtoneManager - รายละเอียดเพิ่มเติม

เมธอดสำคัญ

  • getDefaultUri(int type): ดึง URI เสียง Default ของระบบ
  • getActualDefaultRingtoneUri(Context, int type): ดึง URI ที่ User เลือกตั้งไว้ (รองรับ Custom Ringtone)
  • setActualDefaultRingtoneUri(Context, int type, Uri): ตั้งค่า Default Ringtone ใหม่ (ต้องการ Permission WRITE_SETTINGS)

การใช้ Ringtone Class (Alternative)

// ใช้ Ringtone Class โดยตรง (Simple แต่ควบคุมได้น้อยกว่า MediaPlayer)
Ringtone ringtone = RingtoneManager.getRingtone(context, 
    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
ringtone.play();
// หยุด
ringtone.stop();

AudioAttributes - การตั้งค่าเสียงให้ถูกต้อง

Android 5.0+ (API 21) ต้องระบุ AudioAttributes เพื่อระบบจัดการ Audio Focus ได้ถูกต้อง

Usageใช้สำหรับพฤติกรรมใน Do Not Disturb
USAGE_NOTIFICATIONแจ้งเตือนทั่วไปถูกบล็อกในโหมด DND
USAGE_NOTIFICATION_RINGTONEโทรเข้าอาจเล่นได้ใน DND (ขึ้นอยู่กับ Policy)
USAGE_ALARMนาฬิกาปลุกเล่นได้เสมอใน DND (Critical)
USAGE_MEDIAเพลง, วิดีโอถูกบล็อกใน DND

การใช้งานกับ Notification (Best Practice)

แทนที่จะเล่นเสียง Manual ให้ตั้งค่าที่ Notification Channel (API 26+):

NotificationChannel channel = new NotificationChannel(
    CHANNEL_ID, "Channel Name", NotificationManager.IMPORTANCE_HIGH
);

// ใช้เสียง Default
channel.setSound(
    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),
    new AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_NOTIFICATION)
        .build()
);

// หรือใช้เสียง Custom
channel.setSound(customSoundUri, audioAttributes);

การทดสอบ

  1. รันแอป กดปุ่มแต่ละตัว → ควรได้ยินเสียงประเภทต่างๆ
  2. กด Stop → เสียงหยุดทันที
  3. ลองตั้งโหมด Do Not Disturb → Alarm ควรยังเล่นได้, Notification/Ringtone อาจถูกบล็อก
  4. ไป Settings → Sound → Default notification sound → เปลี่ยนเสียง → ทดสอบอีกครั้ง (ควรเล่นเสียงใหม่)

ข้อควรระวัง

  • MediaPlayer ต้อง prepare() ก่อน start() (เว้นแต่ใช้ create())
  • ต้อง release() ทุกครั้งหลังใช้งาน เพื่อปล่อย Resource
  • ใน Android 13+ อาจต้องขอ Permission POST_NOTIFICATIONS สำหรับ Notification แต่ MediaPlayer ไม่ต้อง
  • เสียง Default อาจเป็น null บนบางอุปกรณ์ → ต้องมี Fallback
แนวทางปัจจุบัน: สำหรับ Notification ให้ใช้ Channel.setSound() สำหรับการเล่นเสียงแยกต่างหาก (Game, Alarm App) ให้ใช้ MediaPlayer + AudioFocus