zaynOm
zaynOm

Reputation: 153

I want to access my systems ringtones in flutter

Is there any way to get all the Ringtones of the phone using flutter, and set the chosen one as the default ringtone of my app?

thanks in advance

Upvotes: 5

Views: 2448

Answers (3)

Deva
Deva

Reputation: 2546

Run the below command to add the flutter plugin where you can access the default ringtone, alarm, notification sound. Also, you can play any custom sound that located in assets folder in the flutter project root directory.

flutter pub add flutter_ringtone_manager

Below are the methods to access the RingtoneManager of the native OS:

FlutterRingtoneManager().playRingtone();
FlutterRingtoneManager().playNotification();
FlutterRingtoneManager().playAudioAsset("audio/test.mp3");

Take a look at the plugin for more clarity.

Upvotes: 0

Imed Boumalek
Imed Boumalek

Reputation: 166

I've made plugin for this a while back

Upvotes: 1

zaynOm
zaynOm

Reputation: 153

I managed to get it done using native code

  1. First you would create those things on the Flutter side.

    
    // here where your ringtones will be stored
    List<Object?> result = ['Andromeda'];
    
    // this is the channel that links flutter with native code
    static const channel = MethodChannel('com.example.pomo_app/mychannel');
    
    // this method waits for results from the native code 
    Future<void> getRingtones() async {
        try {
          result = await channel.invokeMethod('getAllRingtones');
        } on PlatformException catch (ex) {
          print('Exception: $ex.message');
        }
      }
    
    
  2. Know you need to implement the native code. Go to MainActivity.kt

    // add the name of the channel that we made in flutter code
    private val channel = "com.example.pomo_app/mychannel"
    
    // add this method to handle the calls from flutter
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channel)
      .setMethodCallHandler { call, result ->
                when (call.method) {
                    "getAllRingtones" -> {
                        result.success(getAllRingtones(this))
                    }
    
    
    
    // this function will return all the ringtones names as a list
    private fun getAllRingtones(context: Context): List<String> {
    
      val manager = RingtoneManager(context)
      manager.setType(RingtoneManager.TYPE_RINGTONE)
    
      val cursor: Cursor = manager.cursor
    
      val list: MutableList<String> = mutableListOf()
      while (cursor.moveToNext()) {
        val notificationTitle: String = cursor.getString(RingtoneManager.TITLE_COLUMN_INDEX)
        list.add(notificationTitle)
      }
      return list
    }
    

that's it I hope this is helpful. any questions let me know.

Upvotes: 3

Related Questions