You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Cordova获取安卓手机当前设置铃声并在Ionic3闹钟应用播放默认闹钟音

How to Play Android's Default Alarm Ringtone in Ionic 3 App

Got it, let's work through how to get your Ionic 3 Android app to play the system's currently set default alarm ringtone—no custom ringtone settings needed. Since Ionic doesn't have a built-in API for this, we'll leverage Cordova's native capabilities, with two practical solutions:

Option 1: Use an Existing Cordova Plugin (Start Here)

There's a third-party plugin that simplifies accessing system ringtones, including the default alarm tone. Let's use cordova-plugin-ringtone-manager alongside cordova-plugin-media for playback:

Step 1: Install the Required Plugins

Run these commands in your Ionic project root:

# Install ringtone manager plugin and its Ionic Native wrapper
ionic cordova plugin add cordova-plugin-ringtone-manager
npm install @ionic-native/ringtone-manager/ngx

# Install media plugin for audio playback
ionic cordova plugin add cordova-plugin-media
npm install @ionic-native/media/ngx

Step 2: Configure and Use the Plugins

First, register the plugins in your app.module.ts:

import { RingtoneManager } from '@ionic-native/ringtone-manager/ngx';
import { Media } from '@ionic-native/media/ngx';

@NgModule({
  ...
  providers: [
    // Add these to your providers array
    RingtoneManager,
    Media,
    ...
  ]
})
export class AppModule {}

Then, in the page or service where you want to trigger the ringtone, inject the plugins and add this function:

import { RingtoneManager } from '@ionic-native/ringtone-manager/ngx';
import { Media, MediaObject } from '@ionic-native/media/ngx';

constructor(
  private ringtoneManager: RingtoneManager,
  private media: Media
) {}

playDefaultAlarm() {
  // Fetch the URI of the system's default alarm ringtone
  this.ringtoneManager.getRingtoneUri(RingtoneManager.TYPE_ALARM)
    .then(alarmUri => {
      console.log('Default alarm URI:', alarmUri);
      // Create a media object and play the ringtone
      const alarmAudio: MediaObject = this.media.create(alarmUri);
      alarmAudio.play();

      // Don't forget to stop and release resources when done!
      // alarmAudio.stop();
      // alarmAudio.release();
    })
    .catch(err => {
      console.error('Failed to get default alarm:', err);
    });
}

Option 2: Build a Custom Cordova Plugin (If Plugins Don't Work)

If you run into compatibility issues with the third-party plugins, you can write custom Android native code and wrap it into a Cordova plugin:

Step 1: Write the Android Native Code

Create a Java class for your plugin:

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

public class DefaultAlarmPlayer extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("playSystemAlarm")) {
            playDefaultAlarm(callbackContext);
            return true;
        }
        return false;
    }

    private void playDefaultAlarm(CallbackContext callbackContext) {
        try {
            // Get the default alarm URI; fall back to ringtone if none exists
            Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            if (alarmUri == null) {
                alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
            }

            // Play the ringtone
            Ringtone ringtone = RingtoneManager.getRingtone(
                cordova.getActivity().getApplicationContext(), 
                alarmUri
            );
            if (ringtone != null) {
                ringtone.play();
                callbackContext.success("Default alarm playing");
            } else {
                callbackContext.error("Could not load alarm ringtone");
            }
        } catch (Exception e) {
            callbackContext.error(e.getMessage());
        }
    }
}

Step 2: Package as a Cordova Plugin

Follow Cordova's plugin structure to create a plugin.xml and other required files, then add it to your Ionic project:

ionic cordova plugin add /path/to/your/custom-plugin-folder

Step 3: Call the Custom Plugin from Ionic

Use cordova.exec to trigger the native code:

playCustomSystemAlarm() {
  (window as any).cordova.exec(
    (successMsg) => console.log(successMsg),
    (errorMsg) => console.error(errorMsg),
    'DefaultAlarmPlayer', // Match the plugin name from your plugin.xml
    'playSystemAlarm',
    []
  );
}

Important Notes

  • Permissions: Add these to your config.xml to ensure access to ringtones and wake the device if needed:
    <platform name="android">
        <config-file parent="/manifest" target="AndroidManifest.xml">
            <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
            <uses-permission android:name="android.permission.WAKE_LOCK" />
        </config-file>
    </platform>
    
  • Resource Cleanup: Always stop and release media resources after playback to avoid memory leaks.
  • Compatibility: Test on different Android versions—ringtone URIs can vary slightly between OS versions.

内容的提问来源于stack exchange,提问作者Soumya Rauth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:35:30