Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open (audio) file from file manager using Flutter app

When a user tries to open an audio file from his/her file manager I want to show him/her my app in the following "In which app to open this file" pop-up window. After (s)he selects my app from the pop-up window, I want to pass file path into a state variable (currentSong).

I've already managed to add the following IntentFilter into my AndroidManifest.xml. This should correctly show the user my app in the pop-up window:

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data android:scheme="http" />
    <data android:scheme="content" />
    <data android:scheme="file" />
    <data android:mimeType="audio/*" />
    <data android:mimeType="application/ogg" />
    <data android:mimeType="application/x-ogg" />
    <data android:mimeType="application/itunes" />
</intent-filter>

But now I'm just clueless. How to get the file path and save it into the state variable currentSong in Flutter?

like image 401
aleskva Avatar asked Dec 16 '19 21:12

aleskva


People also ask

How do I play audio files in file manager?

The file manager is not intended to play audio file, so this will not work. The Audio-Player app is the right choice for this job. If you want to play files from a folder, I recommend to select the option “folder” in the pull-down in the upper left corner of the app.

How do I open my audio files?

Open File Manager and navigate to the folder where the audio file is located. Drag the audio file icon from File Manager and drop it on the Audio main window. The Selected file is opened. If Automatically play audio file on Open is selected in the Options-Play dialog box, the audio file starts playing.

What is flutter_file_manager?

flutter_file_manager. A set of utilities, that help to manage the files & directories in Android system. You are in your way to create File Manager app or a Gallery App. Usage. To use this package, add these dependency in your pubspec.yaml file. dependencies: flutter: sdk: flutter path: 1.6.2 path_provider: 0.5.0+1 flutter_file_manager: ^0.1.1

How to list and view audio files in flutter?

To list and view Audio Files files from internal/external storage, you have to use flutter_file_manager, path , and path_provider_ex flutter package. Add the following lines in your pubspec.yaml file to add this package in your dependency.

Is there a flutter plugin for music playback?

A flutter plugin for music playback (Flutter Music Player), including notification handling. This plugin is developed for iOS based on AVPlayer, while android is based on mediaplayer Some methods are invalid in the simulator, please use the real machine

How to use Audio_Manager plugin?

The audio_manager plugin is developed in singleton mode. You only need to get AudioManager.instance in the method to quickly start using it. you can use local assets, directory file or network resources // Initial playback.


1 Answers

You need using ChannelPlatform to do that:

1. Android side:

   Handle onCreate + onNewIntent to get bundle data from File Viewer App that share audio file's path

2. Flutter side:

  get audio file's path and do something...

Demo:

Demo share file url with Flutter

Example:

Android

import android.content.Intent
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity : FlutterActivity() {
    private val CHANNEL = "tinyappsteam.flutter.dev/open_file"

    var openPath: String? = null
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when (call.method) {
                "getOpenFileUrl" -> {
                    result.success(openPath)
                }
                else -> result.notImplemented()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handleOpenFileUrl(intent)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handleOpenFileUrl(intent)
    }

    private fun handleOpenFileUrl(intent: Intent?) {
        val path = intent?.data?.path
        if (path != null) {
            openPath = path
        }
    }
}

Flutter:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  static const platform =
      const MethodChannel('tinyappsteam.flutter.dev/open_file');

  String openFileUrl;

  @override
  void initState() {
    super.initState();
    getOpenFileUrl();
    // Listen to lifecycle events.
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      getOpenFileUrl();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text("Audio file: " + (openFileUrl != null ? openFileUrl : "Nothing!")),
      ),
    );
  }

  void getOpenFileUrl() async {
    dynamic url = await platform.invokeMethod("getOpenFileUrl");
    print("getOpenFileUrl");
    if (url != null && url != openFileUrl) {
      setState(() {
        openFileUrl = url;
      });
    }
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
like image 176
duongdt3 Avatar answered Oct 04 '22 21:10

duongdt3