Flutter音频时长获取插件audio_duration的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter音频时长获取插件audio_duration的使用

audio_duration 是一个简单的 Flutter 插件,用于获取任何音频文件(如 mp3)的时长,单位为毫秒。

如何使用

首先,在 pubspec.yaml 文件中添加依赖:

dependencies:
  audio_duration: ^1.0.0

然后在 Dart 代码中导入并使用插件:

import 'package:audio_duration/audio_duration.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Audio Duration Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              // 模拟音频文件路径
              String filePath = "./path/to/the/file.mp3";
              int? durationInMilliseconds = await AudioDuration.getAudioDuration(filePath);
              print("Duration: $durationInMilliseconds ms");
            },
            child: Text('Get Audio Duration'),
          ),
        ),
      ),
    );
  }
}

动机

我需要一个包来在我的个人 Android 应用中获取音频时长。但我在现有的包中没有找到能满足需求的,所以我就创建了这个包。

目前,该插件仅支持 Android。由于我没有 Mac 或 iOS 设备,因此暂时不支持这些平台。不过,欢迎提交 Pull Request。但在提交之前,请先创建一个 Issue。谢谢!

许可证

MIT License

Copyright (c) 2020 Fayaz Bin Salam

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

完整示例代码

以下是一个完整的示例代码,展示了如何使用 audio_duration 插件从用户选择的多个音频文件中获取时长:

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:audio_duration/audio_duration.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _audioDurations = '...';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(_audioDurations),
                ElevatedButton(
                  onPressed: () async {
                    FilePickerResult? result = await FilePicker.platform.pickFiles(
                      allowMultiple: true,
                      type: FileType.audio,
                    );

                    if (result != null) {
                      List<File> files = result.paths.map((path) => File(path!)).toList();
                      List<String> urls = files.map((e) {
                        String path = e.uri.toFilePath();
                        return path;
                      }).toList();
                      urls.sort((a, b) => a.compareTo(b));

                      var finalText = "";
                      for (var i = 0; i < urls.length; i++) {
                        var duration = await AudioDuration.getAudioDuration(urls[i]);
                        finalText += "${urls[i]} - ${duration!}\n";
                      }

                      setState(() {
                        _audioDurations = finalText;
                      });
                    }
                  },
                  child: const Text("Pick files"),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

在这个示例中,用户可以通过点击按钮选择多个音频文件,然后应用会显示每个文件的路径及其对应的时长。希望这个示例对你有帮助!


更多关于Flutter音频时长获取插件audio_duration的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter音频时长获取插件audio_duration的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用audio_duration插件来获取音频文件时长的示例代码。这个插件允许你读取本地或网络上的音频文件并获取其时长。

首先,确保你已经在pubspec.yaml文件中添加了audio_duration依赖:

dependencies:
  flutter:
    sdk: flutter
  audio_duration: ^0.1.7  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter应用中按照以下步骤使用audio_duration插件:

  1. 导入插件

在你的Dart文件中导入audio_duration插件:

import 'package:audio_duration/audio_duration.dart';
  1. 获取音频时长

以下是一个完整的示例,展示如何获取本地或网络音频文件的时长:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AudioDurationScreen(),
    );
  }
}

class AudioDurationScreen extends StatefulWidget {
  @override
  _AudioDurationScreenState createState() => _AudioDurationScreenState();
}

class _AudioDurationScreenState extends State<AudioDurationScreen> {
  String audioPath; // 本地或网络音频文件的路径
  String durationText = "Loading duration...";

  @override
  void initState() {
    super.initState();
    // 示例音频路径,可以是本地路径或网络URL
    audioPath = "assets/audio/sample.mp3"; // 本地文件路径
    // audioPath = "https://example.com/audio/sample.mp3"; // 网络文件URL

    _getAudioDuration(audioPath);
  }

  Future<void> _getAudioDuration(String path) async {
    try {
      final AudioDuration audioDuration = AudioDuration(path);
      final Duration duration = await audioDuration.getDuration();
      setState(() {
        durationText = "${duration.inMinutes}:${duration.inSeconds % 60.toInt().toString().padLeft(2, '0')}";
      });
    } catch (e) {
      setState(() {
        durationText = "Error: ${e.message}";
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Duration Example'),
      ),
      body: Center(
        child: Text(
          durationText,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

注意事项:

  1. 本地文件:如果你使用本地文件,请确保在pubspec.yaml文件中声明了资源文件,并且在项目中正确放置了音频文件。例如:
flutter:
  assets:
    - assets/audio/sample.mp3
  1. 网络文件:如果你使用网络音频文件,请确保URL是有效的,并且你的应用有权限访问网络。

  2. 错误处理:在实际应用中,你应该添加更多的错误处理逻辑,以应对可能发生的各种异常情况,例如网络错误、文件不存在等。

  3. 插件版本:请检查audio_duration插件的最新版本,并根据需要更新代码中的版本号。

这个示例展示了如何使用audio_duration插件来异步获取音频文件的时长,并在UI中显示结果。

回到顶部