国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

flutter中使用基于flutter_sound的flutter_sound_record錄音

這篇具有很好參考價值的文章主要介紹了flutter中使用基于flutter_sound的flutter_sound_record錄音。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言

使用flutter_sound,總是出現(xiàn)莫名的錯誤,所以改為flutter_sound_record,實現(xiàn)錄音錄制和播放

文章案例所使用插件的版本號

3.3.2

插件安裝

安裝方式:
命令行形式:

flutter pub add flutter_sound_record

pubspec.yaml格式 (別忘運行 pub get):

dependencies:
  flutter_sound_record: ^3.3.2

引入

import 'package:flutter_sound_record/flutter_sound_record.dart';

引入安卓和ios權(quán)限

Android

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Optional, you'll have to check this permission by yourself. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

min SDK: 16 (29 if you use OPUS)

iOs

<key>NSMicrophoneUsageDescription</key>
<string>We need to access to the microphone to record audio file</string>

min SDK: 8.0 (11 if you use OPUS)

支持的編碼

enum AudioEncoder {
  /// Will output to MPEG_4 format container
  AAC,

  /// Will output to MPEG_4 format container
  AAC_LD,

  /// Will output to MPEG_4 format container
  AAC_HE,

  /// sampling rate should be set to 8kHz
  /// Will output to 3GP format container on Android
  AMR_NB,

  /// sampling rate should be set to 16kHz
  /// Will output to 3GP format container on Android
  AMR_WB,

  /// Will output to MPEG_4 format container
  /// /!\ SDK 29 on Android /!\
  /// /!\ SDK 11 on iOs /!\
  OPUS,
}

自定義生成的文件名

在下面main.dart的代碼中的 _start() 函數(shù)

await _audioRecorder.start();
//path改為自定義的即可,其余參數(shù)根據(jù)自己需求設(shè)置
await _audioRecorder.start(
  path: 'aFullPath/myFile.m4a', // required
  encoder: AudioEncoder.AAC, // by default
  bitRate: 128000, // by default
  sampleRate: 44100, // by default
);

代碼

main.dart
import 'dart:async';

import 'package:example/audio_player.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound_record/flutter_sound_record.dart';
import 'package:just_audio/just_audio.dart' as ap;

class AudioRecorder extends StatefulWidget {
  const AudioRecorder({required this.onStop, Key? key}) : super(key: key);

  final void Function(String path) onStop;

  @override
  _AudioRecorderState createState() => _AudioRecorderState();
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(ObjectFlagProperty<void Function(String path)>.has('onStop', onStop));
  }
}

class _AudioRecorderState extends State<AudioRecorder> {
  bool _isRecording = false;
  bool _isPaused = false;
  int _recordDuration = 0;
  Timer? _timer;
  Timer? _ampTimer;
  final FlutterSoundRecord _audioRecorder = FlutterSoundRecord();
  Amplitude? _amplitude;

  @override
  void initState() {
    _isRecording = false;
    super.initState();
  }

  @override
  void dispose() {
    _timer?.cancel();
    _ampTimer?.cancel();
    _audioRecorder.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                _buildRecordStopControl(),
                const SizedBox(width: 20),
                _buildPauseResumeControl(),
                const SizedBox(width: 20),
                _buildText(),
              ],
            ),
            if (_amplitude != null) ...<Widget>[
              const SizedBox(height: 40),
              Text('Current: ${_amplitude?.current ?? 0.0}'),
              Text('Max: ${_amplitude?.max ?? 0.0}'),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildRecordStopControl() {
    late Icon icon;
    late Color color;

    if (_isRecording || _isPaused) {
      icon = const Icon(Icons.stop, color: Colors.red, size: 30);
      color = Colors.red.withOpacity(0.1);
    } else {
      final ThemeData theme = Theme.of(context);
      icon = Icon(Icons.mic, color: theme.primaryColor, size: 30);
      color = theme.primaryColor.withOpacity(0.1);
    }

    return ClipOval(
      child: Material(
        color: color,
        child: InkWell(
          child: SizedBox(width: 56, height: 56, child: icon),
          onTap: () {
            _isRecording ? _stop() : _start();
          },
        ),
      ),
    );
  }

  Widget _buildPauseResumeControl() {
    if (!_isRecording && !_isPaused) {
      return const SizedBox.shrink();
    }

    late Icon icon;
    late Color color;

    if (!_isPaused) {
      icon = const Icon(Icons.pause, color: Colors.red, size: 30);
      color = Colors.red.withOpacity(0.1);
    } else {
      final ThemeData theme = Theme.of(context);
      icon = const Icon(Icons.play_arrow, color: Colors.red, size: 30);
      color = theme.primaryColor.withOpacity(0.1);
    }

    return ClipOval(
      child: Material(
        color: color,
        child: InkWell(
          child: SizedBox(width: 56, height: 56, child: icon),
          onTap: () {
            _isPaused ? _resume() : _pause();
          },
        ),
      ),
    );
  }

  Widget _buildText() {
    if (_isRecording || _isPaused) {
      return _buildTimer();
    }

    return const Text('Waiting to record');
  }

  Widget _buildTimer() {
    final String minutes = _formatNumber(_recordDuration ~/ 60);
    final String seconds = _formatNumber(_recordDuration % 60);

    return Text(
      '$minutes : $seconds',
      style: const TextStyle(color: Colors.red),
    );
  }

  String _formatNumber(int number) {
    String numberStr = number.toString();
    if (number < 10) {
      numberStr = '0$numberStr';
    }

    return numberStr;
  }

  Future<void> _start() async {
    try {
      if (await _audioRecorder.hasPermission()) {
        await _audioRecorder.start();

        bool isRecording = await _audioRecorder.isRecording();
        setState(() {
          _isRecording = isRecording;
          _recordDuration = 0;
        });

        _startTimer();
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  Future<void> _stop() async {
    _timer?.cancel();
    _ampTimer?.cancel();
    final String? path = await _audioRecorder.stop();

    widget.onStop(path!);

    setState(() => _isRecording = false);
  }

  Future<void> _pause() async {
    _timer?.cancel();
    _ampTimer?.cancel();
    await _audioRecorder.pause();

    setState(() => _isPaused = true);
  }

  Future<void> _resume() async {
    _startTimer();
    await _audioRecorder.resume();

    setState(() => _isPaused = false);
  }

  void _startTimer() {
    _timer?.cancel();
    _ampTimer?.cancel();

    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      setState(() => _recordDuration++);
    });

    _ampTimer = Timer.periodic(const Duration(milliseconds: 200), (Timer t) async {
      _amplitude = await _audioRecorder.getAmplitude();
      setState(() {});
    });
  }
}

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool showPlayer = false;
  ap.AudioSource? audioSource;

  @override
  void initState() {
    showPlayer = false;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: showPlayer
              ? Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: AudioPlayer(
                    source: audioSource!,
                    onDelete: () {
                      setState(() => showPlayer = false);
                    },
                  ),
                )
              : AudioRecorder(
                  onStop: (String path) {
                    setState(() {
                      audioSource = ap.AudioSource.uri(Uri.parse(path));
                      showPlayer = true;
                    });
                  },
                ),
        ),
      ),
    );
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<bool>('showPlayer', showPlayer));
    properties.add(DiagnosticsProperty<ap.AudioSource?>('audioSource', audioSource));
  }
}

audio_player.dart
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart' as ap;

class AudioPlayer extends StatefulWidget {
  const AudioPlayer({
    required this.source,
    required this.onDelete,
    Key? key,
  }) : super(key: key);

  /// Path from where to play recorded audio
  final ap.AudioSource source;

  /// Callback when audio file should be removed
  /// Setting this to null hides the delete button
  final VoidCallback onDelete;

  @override
  AudioPlayerState createState() => AudioPlayerState();
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<ap.AudioSource>('source', source));
    properties.add(ObjectFlagProperty<VoidCallback>.has('onDelete', onDelete));
  }
}

class AudioPlayerState extends State<AudioPlayer> {
  static const double _controlSize = 56;
  static const double _deleteBtnSize = 24;

  final ap.AudioPlayer _audioPlayer = ap.AudioPlayer();
  late StreamSubscription<ap.PlayerState> _playerStateChangedSubscription;
  late StreamSubscription<Duration?> _durationChangedSubscription;
  late StreamSubscription<Duration> _positionChangedSubscription;

  @override
  void initState() {
    _playerStateChangedSubscription = _audioPlayer.playerStateStream.listen((ap.PlayerState state) async {
      if (state.processingState == ap.ProcessingState.completed) {
        await stop();
      }
      setState(() {});
    });
    _positionChangedSubscription = _audioPlayer.positionStream.listen((Duration position) => setState(() {}));
    _durationChangedSubscription = _audioPlayer.durationStream.listen((Duration? duration) => setState(() {}));
    _init();

    super.initState();
  }

  Future<void> _init() async {
    await _audioPlayer.setAudioSource(widget.source);
  }

  @override
  void dispose() {
    _playerStateChangedSubscription.cancel();
    _positionChangedSubscription.cancel();
    _durationChangedSubscription.cancel();
    _audioPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            _buildControl(),
            _buildSlider(constraints.maxWidth),
            IconButton(
              icon: const Icon(
                Icons.delete,
                color: Color(0xFF73748D),
                size: _deleteBtnSize,
              ),
              onPressed: () {
                // ignore: always_specify_types
                _audioPlayer.stop().then((value) => widget.onDelete());
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildControl() {
    Icon icon;
    Color color;

    if (_audioPlayer.playerState.playing) {
      icon = const Icon(Icons.pause, color: Colors.red, size: 30);
      color = Colors.red.withOpacity(0.1);
    } else {
      final ThemeData theme = Theme.of(context);
      icon = Icon(Icons.play_arrow, color: theme.primaryColor, size: 30);
      color = theme.primaryColor.withOpacity(0.1);
    }

    return ClipOval(
      child: Material(
        color: color,
        child: InkWell(
          child: SizedBox(width: _controlSize, height: _controlSize, child: icon),
          onTap: () {
            if (_audioPlayer.playerState.playing) {
              pause();
            } else {
              play();
            }
          },
        ),
      ),
    );
  }

  Widget _buildSlider(double widgetWidth) {
    final Duration position = _audioPlayer.position;
    final Duration? duration = _audioPlayer.duration;
    bool canSetValue = false;
    if (duration != null) {
      canSetValue = position.inMilliseconds > 0;
      canSetValue &= position.inMilliseconds < duration.inMilliseconds;
    }

    double width = widgetWidth - _controlSize - _deleteBtnSize;
    width -= _deleteBtnSize;

    return SizedBox(
      width: width,
      child: Slider(
        activeColor: Theme.of(context).primaryColor,
        inactiveColor: Theme.of(context).colorScheme.secondary,
        onChanged: (double v) {
          if (duration != null) {
            final double position = v * duration.inMilliseconds;
            _audioPlayer.seek(Duration(milliseconds: position.round()));
          }
        },
        value: canSetValue && duration != null ? position.inMilliseconds / duration.inMilliseconds : 0.0,
      ),
    );
  }

  Future<void> play() {
    return _audioPlayer.play();
  }

  Future<void> pause() {
    return _audioPlayer.pause();
  }

  Future<void> stop() async {
    await _audioPlayer.stop();
    return _audioPlayer.seek(Duration.zero);
  }
}

源碼地址

https://github.com/josephcrowell/flutter_sound_record/文章來源地址http://www.zghlxwxcb.cn/news/detail-812575.html

到了這里,關(guān)于flutter中使用基于flutter_sound的flutter_sound_record錄音的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 使用Jmeter自帶recorder代理服務(wù)器錄制接口腳本

    使用Jmeter自帶recorder代理服務(wù)器錄制接口腳本

    腳本錄制 配置線程組 添加代理服務(wù)器 端口 和 錄制腳本放置位置可根據(jù)需要設(shè)置 啟動錄制 點擊啟動后 彈出創(chuàng)建證書提示,點擊OK 這個證書后續(xù)需要使用到 然后可見 一個彈窗。 Recorder . 本質(zhì)是代理服務(wù)+錄制交易控制 可設(shè)置對應(yīng)數(shù)據(jù) 方便錄制腳本的查看 證書配置 Jmeter 證書

    2024年02月12日
    瀏覽(20)
  • 使用Java 17中的record替代Lombok的部分功能

    在DD長期更新的Java新特性專欄中,已經(jīng)介紹過Java 16中開始支持的新特性:record的使用。 之前只是做了介紹,但沒有結(jié)合之前的編碼習(xí)慣或規(guī)范來聊聊未來的應(yīng)用變化。最近正好因為互相review一些合作伙伴的代碼,產(chǎn)生了一些討論話題,主要正針對于有了 record 之后,其實之前

    2024年02月02日
    瀏覽(19)
  • 關(guān)于在 Mybatis 中使用 record 關(guān)鍵字來定義 JavaBean

    經(jīng)測試,正常情況下使用 record 是沒有問題的,但若是使用了 resultMap,將會導(dǎo)致錯誤: 首先, record 類型沒有 無參構(gòu)造函數(shù) ,所以在反射過程中無法創(chuàng)建對應(yīng)類型,導(dǎo)致了 argument type mismatch 錯誤。 那如果給 record 類型的類加上無參構(gòu)造函數(shù)呢? 會出現(xiàn)以下錯誤: 可以看到

    2024年02月05日
    瀏覽(24)
  • 【AI視野·今日Sound 聲學(xué)論文速覽 第八期】Wed, 20 Sep 2023

    【AI視野·今日Sound 聲學(xué)論文速覽 第八期】Wed, 20 Sep 2023

    AI視野 ·今日CS.Sound 聲學(xué)論文速覽 Wed, 20 Sep 2023 Totally 1 papers ?? 上期速覽 ?更多精彩請移步主頁 Accelerating Diffusion-Based Text-to-Audio Generation with Consistency Distillation Authors Yatong Bai, Trung Dang, Dung Tran, Kazuhito Koishida, Somayeh Sojoudi 擴散模型為絕大多數(shù)文本到音頻 TTA 生成方法提供支持。

    2024年02月08日
    瀏覽(16)
  • vue3+ts中使用mitt跨組件通信報錯:沒有與此調(diào)用匹配的重載。handler: WildcardHandler<Record<EventType, unknown>>

    vue3+ts中使用mitt跨組件通信報錯:沒有與此調(diào)用匹配的重載。handler: WildcardHandler<Record<EventType, unknown>>

    報錯內(nèi)容如下圖: mitt代碼的使用方式: mittBus.js文件: 經(jīng)過多方資料查閱,總結(jié)出問題出現(xiàn)的原因是ts中的類型推斷異常 。mittBus的參數(shù)無法推斷出來。 如果使用的是最新的 mitt@3.0.0 版本,在ts中使用mitt時需要添加類型注解,去官網(wǎng)查閱使用方式如下: Usage : 1、Set “stri

    2023年04月22日
    瀏覽(57)
  • Linux音頻處理:MP3解碼、PCM、播放PCM、ALSA(Advanced Linux Sound Architecture)、MPEG(Moving Picture Experts Group)

    將MP3音頻文件中的數(shù)字音頻數(shù)據(jù)轉(zhuǎn)換為可以播放或處理的音頻信號的過程。MP3(MPEG-1 Audio Layer 3)是一種常見的音頻壓縮格式,用于將音頻文件壓縮到較小的文件大小,同時保持相對高的音質(zhì)。 以下是MP3解碼的一般步驟: 讀取MP3文件 : 首先,需要讀取存儲在MP3文件中的音頻

    2024年02月03日
    瀏覽(18)
  • Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(上)

    Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(上)

    Flutter筆記 完全基于Flutter繪圖技術(shù)繪制一個精美的Dart語言吉祥物Dash(上) 作者 : 李俊才 (jcLee95):https://blog.csdn.net/qq_28550263 郵箱 : 291148484@163.com 本文地址 :https://blog.csdn.net/qq_28550263/article/details/134098877 【介紹】:本文完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(上

    2024年02月07日
    瀏覽(38)
  • Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(中)

    Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(中)

    Flutter筆記 完全基于Flutter繪圖技術(shù)繪制一個精美的Dart語言吉祥物Dash(中) 作者 : 李俊才 (jcLee95):https://blog.csdn.net/qq_28550263 郵箱 : 291148484@163.com 本文地址 :https://blog.csdn.net/qq_28550263/article/details/134098877 【介紹】:本文完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(中

    2024年02月06日
    瀏覽(25)
  • Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(下)

    Flutter筆記:完全基于Flutter繪圖技術(shù)繪制一個精美的Dash圖標(下)

    Flutter筆記 完全基于Flutter繪圖技術(shù)繪制一個精美的Dart吉祥物Dash 作者 : 李俊才 (jcLee95):https://blog.csdn.net/qq_28550263 郵箱 : 291148484@163.com 本文地址 :https://blog.csdn.net/qq_28550263/article/details/134098955 另見: 上上篇文章:《完全基于Flutter繪圖技術(shù)繪制一個精美的Dart語言吉祥物

    2024年02月07日
    瀏覽(39)
  • flutter實現(xiàn)下拉菜單組件——基于PopupMenuButton

    flutter實現(xiàn)下拉菜單組件——基于PopupMenuButton

    客戶端日常開發(fā)和學(xué)習(xí)過程,下拉菜單是一個很常見的組件,本文主要介紹flutter中實現(xiàn)下拉菜單組件的一個方案,基于PopupMenuButton來進行實現(xiàn)。 PopupMenuButton PopupMenuButton 是一個非常常見的彈出菜單欄。 屬性介紹: 話不多說,直接上代碼 (1)新建MenuItem.dart通用菜單項類,代碼

    2024年02月07日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包