audio_picker_utils.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import 'dart:io';
  2. import 'package:file_picker/file_picker.dart';
  3. import 'package:photo_manager/photo_manager.dart';
  4. class AudioPickerUtils {
  5. AudioPickerUtils._();
  6. //申请权限
  7. static Future<bool> requestPermissionExtend() async {
  8. final PermissionState ps = await PhotoManager.requestPermissionExtend(
  9. requestOption: const PermissionRequestOption(
  10. androidPermission: AndroidPermission(
  11. type: RequestType.audio,
  12. mediaLocation: false,
  13. )));
  14. return ps.hasAccess;
  15. }
  16. //是否有权限
  17. static Future<bool> hasPermission() async {
  18. final PermissionState ps = await PhotoManager.getPermissionState(
  19. requestOption: const PermissionRequestOption());
  20. return ps.hasAccess;
  21. }
  22. //获取AssetPathEntity
  23. static Future<List<AssetPathEntity>> getAssetPathList() async {
  24. final PMFilter filter = FilterOptionGroup(
  25. audioOption: const FilterOption(
  26. sizeConstraint: SizeConstraint(ignoreSize: true),
  27. ),
  28. );
  29. final List<AssetPathEntity> paths = await PhotoManager.getAssetPathList(
  30. onlyAll: true,
  31. type: RequestType.audio,
  32. filterOption: filter,
  33. );
  34. return paths;
  35. }
  36. //获取本地音频资源列表
  37. static Future<List<AssetEntity>> getAssetListPaged(
  38. AssetPathEntity path, int page, int size) async {
  39. final List<AssetEntity> entities = await path.getAssetListPaged(
  40. page: page,
  41. size: size,
  42. );
  43. return entities;
  44. }
  45. static Future<List<AssetEntity>> getAssetListRange(
  46. AssetPathEntity path, int offset, int limit) async {
  47. final List<AssetEntity> entities = await path.getAssetListRange(
  48. start: offset,
  49. end: offset + limit,
  50. );
  51. return entities;
  52. }
  53. //根据id获取AssetEntity
  54. static Future<AssetEntity?> getAssetEntity(String? id) async {
  55. if (id == null) {
  56. return null;
  57. }
  58. return await AssetEntity.fromId(id);
  59. }
  60. //根据id获取文件
  61. static Future<File?> getAssetFile(String? id) async {
  62. if (id == null) {
  63. return null;
  64. }
  65. AssetEntity? assetEntity = await AssetEntity.fromId(id);
  66. return await assetEntity?.file;
  67. }
  68. //通过平台文件管理器的方式选择单一文件
  69. static Future<File?> pickSingleFileByPlatform() async {
  70. FilePickerResult? result = await FilePicker.platform
  71. .pickFiles(type: FileType.custom, allowedExtensions: [
  72. 'wav',
  73. 'mp3',
  74. 'm4a',
  75. 'flv',
  76. 'mp4',
  77. 'wma',
  78. '3gp',
  79. 'amr',
  80. 'aac',
  81. 'ogg-opus',
  82. 'flac'
  83. ]);
  84. if (result != null) {
  85. String filePath = result.files.single.path!;
  86. File file = File(filePath);
  87. return file;
  88. }
  89. return null;
  90. }
  91. }