Flutter音频分析插件audio_analyzer的使用

Flutter音频分析插件audio_analyzer的使用

audio_analyzer 是一个用于获取音频文件振幅数据的 Flutter 插件。在 Android 端,该插件利用了 Amplituda 库。

特性

  • 获取音频文件的振幅数据

安装

在项目的 pubspec.yaml 文件中添加依赖:

dependencies:
  audio_analyzer: ^0.0.1

对于 Android,还需要在项目的 build.gradle 文件(项目级别)中添加以下内容:

allprojects {
    repositories {
         maven { url 'https://jitpack.io' }
    }
}

在 iOS 上,应该可以直接使用。

使用

首先,导入包:

import 'package:audio_analyzer/audio_analyzer.dart';

获取振幅

要从音频文件中获取振幅数据:

try {
  List<int> amplitudes = await AudioAnalyzer.getAmplitudes('path/to/your/audio/file.mp3');
  // 处理振幅数据
} catch (e) {
  print('Error: $e');
}

示例

以下是一个完整的示例,演示如何使用 audio_analyzer 插件来获取音频文件的振幅数据:

import 'dart:async';

import 'package:audio_analyzer/audio_analyzer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.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 _amplitudeResult = 'Unknown';
  final _audioAnalyzerPlugin = AudioAnalyzer();

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

  Future<void> getAmplitude() async {
    String amplitudeResult;
    try {
      final result = await FilePicker.platform.pickFiles(
        type: FileType.audio,
        allowMultiple: false,
      );

      if (result == null || result.files.isEmpty) {
        amplitudeResult = 'No file selected';
        return;
      }

      final filePath = result.files.single.path;
      if (filePath == null) {
        amplitudeResult = 'Invalid file path';
        return;
      }

      List<int> amplitudes =
          await _audioAnalyzerPlugin.getAmplitudes(result.files.single.path!);
      amplitudeResult = 'Amplitude: $amplitudes';
    } on Exception catch (e) {
      amplitudeResult = 'Error: $e';
    }

    setState(() {
      _amplitudeResult = amplitudeResult;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('振幅分析器示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SelectableText(_amplitudeResult),
              ElevatedButton(
                onPressed: getAmplitude,
                child: const Text('获取振幅'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

要求

  • Android SDK 21+
  • Flutter 2.0.0+

限制

iOS 和 Android 的结果略有不同。例如,使用长度为 2 秒的同一音频文件进行测试时:

  • Android 输出:
amplitudes = [0, 0, 0, 0, 0, 3, 7, 10, 11, 8, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 10, 13, 14, 11, 5, 1, 1, 0, 0, 0, 2, 11, 11, 11, 12, 12, 12, 10, 12, 10, 6, 1, 0, 1, 9, 9, 4, 0, 1, 2, 5, 11, 11, 9, 7, 2, 0, 0, 1, 0, 5, 10, 9, 2, 0, 0, 1, 9, 12, 8, 2, 1, 2, 1, 0, 0, 7, 17, 14, 12, 11, 10, 8, 7, 5, 3, 2, 1, 1, 0, 0, 0]
amplitudes.length = 92
  • iOS 输出:
amplitudes = [0, 0, 0, 0, 0, 3, 8, 10, 10, 6, 0, 0, 0, 1, 1, 0, 0, 1, 1, 8, 13, 14, 11, 6, 1, 1, 0, 0, 0, 4, 11, 11, 11, 12, 13, 11, 12, 12, 8, 3, 0, 1, 7, 10, 5, 0, 1, 2, 4, 11, 11, 9, 7, 2, 0, 1, 1, 1, 7, 10, 7, 1, 0, 0, 6, 12, 10, 3, 1, 2, 1, 0, 0, 7, 16, 14, 12, 11, 10, 8, 7, 5, 3, 2, 1, 1, 0, 0, 0, 0, 0]
amplitudes.length = 91

更多关于Flutter音频分析插件audio_analyzer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,下面是一个关于如何使用 audio_analyzer 插件在 Flutter 中进行音频分析的示例代码。这个示例将展示如何初始化音频分析器、开始和停止录音以及获取音频数据。

首先,确保在你的 pubspec.yaml 文件中添加 audio_analyzer 依赖:

dependencies:
  flutter:
    sdk: flutter
  audio_analyzer: ^最新版本号  # 请替换为当前最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来是示例代码:

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

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

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

class AudioAnalyzerScreen extends StatefulWidget {
  @override
  _AudioAnalyzerScreenState createState() => _AudioAnalyzerScreenState();
}

class _AudioAnalyzerScreenState extends State<AudioAnalyzerScreen> {
  late AudioAnalyzer _audioAnalyzer;
  bool _isRecording = false;

  @override
  void initState() {
    super.initState();
    _audioAnalyzer = AudioAnalyzer();
    _audioAnalyzer.initialize().then((_) {
      print("Audio Analyzer Initialized");
    }).catchError((error) {
      print("Failed to initialize audio analyzer: $error");
    });
  }

  @override
  void dispose() {
    _audioAnalyzer.dispose();
    super.dispose();
  }

  void _startRecording() async {
    if (!_isRecording) {
      setState(() {
        _isRecording = true;
      });

      _audioAnalyzer.startRecording().then((_) {
        print("Recording started");
        _audioAnalyzer.onAudioDataReceived.listen((data) {
          // 在这里处理音频数据
          print("Audio Data Received: ${data.map((e) => e.toDouble()).toList()}");
        });
      }).catchError((error) {
        print("Failed to start recording: $error");
        setState(() {
          _isRecording = false;
        });
      });
    }
  }

  void _stopRecording() async {
    if (_isRecording) {
      setState(() {
        _isRecording = false;
      });

      _audioAnalyzer.stopRecording().then((_) {
        print("Recording stopped");
      }).catchError((error) {
        print("Failed to stop recording: $error");
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Analyzer Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _startRecording,
              child: Text('Start Recording'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _stopRecording,
              child: Text('Stop Recording'),
            ),
          ],
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在 pubspec.yaml 中添加 audio_analyzer 依赖。
  2. 初始化:在 initState 方法中初始化 AudioAnalyzer 对象。
  3. 开始录音_startRecording 方法用于开始录音,并监听 onAudioDataReceived 事件以获取音频数据。
  4. 停止录音_stopRecording 方法用于停止录音。
  5. UI:简单的 Flutter 界面,包含两个按钮用于开始和停止录音。

请注意,audio_analyzer 插件的具体 API 和使用方法可能会随着版本更新而变化。因此,请务必查阅最新的官方文档以获取最准确的信息。

此外,由于音频分析涉及实时数据处理,因此在实际应用中可能需要更复杂的逻辑来处理音频数据并进行相应的分析。

回到顶部