9.1.flutter-音频

作者: ChaosHeart | 来源:发表于2021-05-06 18:29 被阅读0次

一:音频管理类

import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:path_provider/path_provider.dart';

///实例
var audioPlayerManager = AudioPlayerManager();

///类
class AudioPlayerManager {
  // 工厂方法构造函数
  factory AudioPlayerManager() => _getInstance();

  // instance的getter方法,singletonManager.instance获取对象
  static AudioPlayerManager get instance => _getInstance();

  // 静态变量_instance,存储唯一对象
  static AudioPlayerManager _instance;

  // 获取对象
  static AudioPlayerManager _getInstance() {
    if (_instance == null) {
      // 使用私有的构造方法来创建对象
      _instance = AudioPlayerManager._internal();
    }
    return _instance;
  }

  // 私有的命名式构造方法,通过它实现一个类 可以有多个构造函数,
  // 子类不能继承internal
  // 不是关键字,可定义其他名字
  AudioPlayerManager._internal() {
    //初始化...
    _audioCache = AudioCache();
    audioPlayer = AudioPlayer();
    print("初始化成功...");
  }

  //以上为单例...

  //音频缓存
  AudioCache _audioCache;

  ///播放
  loadAudioCache(String fileName) {
    //播放给定的[fileName]。
    //
    //如果文件已经缓存,它会立即播放。否则,首先等待文件加载(可能需要几毫秒)。
    //它创建一个新的实例[AudioPlayer],所以它不会影响其他的音频播放(除非你指定一个[fixedPlayer],在这种情况下它总是使用相同的)。
    //返回实例,以允许以后的访问(无论哪种方式),如暂停和恢复。
    _audioCache.play(fileName, mode: PlayerMode.LOW_LATENCY);
  }

  //音频播放器
  AudioPlayer audioPlayer;
  //音频文件夹
  Map<String, File> loadedFiles = {};

  ///清空单个
  void clear(String fileName) {
    loadedFiles.remove(fileName);
  }

  ///清空整个
  void clearCache() {
    loadedFiles.clear();
  }

  ///文件中
  Future<ByteData> _fetchAsset(String fileName) async {
    return await rootBundle.load('music/$fileName');
  }

  ///内存中
  Future<File> fetchToMemory(String fileName) async {
    final file = File('${(await getTemporaryDirectory()).path}/$fileName');
    await file.create(recursive: true);
    return await file
        .writeAsBytes((await _fetchAsset(fileName)).buffer.asUint8List());
  }

  ///读取文件
  Future<File> loadFile(String fileName) async {
    if (!loadedFiles.containsKey(fileName)) {
      loadedFiles[fileName] = await fetchToMemory(fileName); //这里添加
    }
    return loadedFiles[fileName];
  }

  ///本地播放
  ///path 路径
  playAsset(String path) async {
    //读取文件
    File file = await loadFile(path);
    //播放音频。
    //
    //如果[isLocal]为true, [url]必须是本地文件系统路径。
    //如果[isLocal]为false,则[url]必须是远程url。
    //volume 音量
    int result = await audioPlayer.play(file.path, isLocal: true, volume: 0.2);
    if (result == 1) {
      print('play success');
    } else {
      print('play failed');
    }
  }

  ///网络播放
  ///url 网址
  playNetwork(String url) async {
    //播放音频。
    //
    //如果[isLocal]为true, [url]必须是本地文件系统路径。
    //如果[isLocal]为false,则[url]必须是远程url。
    //volume 音量
    int result = await audioPlayer.play(url, isLocal: false, volume: 0.2);
    if (result == 1) {
      print('play success');
    } else {
      print('play failed');
    }
  }

  ///暂停
  pause() async {
    //暂停当前播放的音频。
    //
    //如果你稍后调用[resume],音频将从它的点恢复
    //已暂停。
    int result = await audioPlayer.pause();
    if (result == 1) {
      print('pause success');
    } else {
      print('pause failed');
    }
  }

  ///调整进度 - 跳转指定时间
  ///milliseconds 毫秒
  jump(int milliseconds) async {
    //移动光标到目标位置。
    int result =
        await audioPlayer.seek(new Duration(milliseconds: milliseconds));
    if (result == 1) {
      print('seek to success');
    } else {
      print('seek to failed');
    }
  }

  ///调整音量
  ///double volume 音量 0-1
  setVolume(double volume) async {
    //设置音量(振幅)。
    //
    // 0表示静音,1表示最大音量。0到1之间的值是线性的
    int result = await audioPlayer.setVolume(volume);
    if (result == 1) {
      print('seek to success');
    } else {
      print('seek to failed');
    }
  }

  ///释放资源
  release() async {
    //释放与该媒体播放器关联的资源。
    //
    //当你需要重新获取资源时,你需要重新获取资源
    //调用[play]或[setUrl]。
    int result = await audioPlayer.release();
    if (result == 1) {
      print('release success');
    } else {
      print('release failed');
    }
  }
}

二:音频调用

import 'package:audio_players/audio_player_manager.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';

///音频播放页
class AudioPlayerPage extends StatefulWidget {
  final String title;

  AudioPlayerPage({Key key, this.title}) : super(key: key);

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

class _AudioPlayerPageState extends State<AudioPlayerPage> {
  //音乐资源路径
  List<String> _musicList = [
    "0.wav",
    "1.mp3",
    "2.mp3",
    "3.mp3",
    "4.mp3",
  ];

  //音乐下表
  int _index = 0;

  //初始音量
  double _volume = 0.2;

  //当前毫秒
  int milliseconds = 0;

  //总时间
  int total = 100000000000;

  //是否暂停
  bool _isPause = true;

  //默认状态
  AudioPlayerState _state = AudioPlayerState.STOPPED;

  //以上为属性...

  ///init
  @override
  void initState() {
    super.initState();
    //监听播放位置
    _listenAudioPositionChanged();
    //监听播放器当前状态
    _listenAudioPlayerStateController();
  }

  ///deactivate
  @override
  void deactivate() {
    ///释放资源
    audioPlayerManager.release();
    super.deactivate();
  }

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

  ///build
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            //播放
            RaisedButton(
              child: Text(
                _isPause ? "播放" : "暂停",
                style: TextStyle(),
              ),
              onPressed: () {
                if (_isPause) {
                  _isPause = false;
                  String path = "${_musicList[_index]}";
                  audioPlayerManager.playAsset(path);
                } else {
                  _isPause = true;
                  audioPlayerManager.pause();
                }
                setState(() {});
              },
            ),
            //增大音量
            RaisedButton(
              child: Text(
                "增大音量",
                style: TextStyle(),
              ),
              onPressed: () {
                _volume += 0.3;
                if (_volume == 1) {
                  _volume = 1;
                }
                audioPlayerManager.setVolume(_volume);
              },
            ),
            //减小音量
            RaisedButton(
              child: Text(
                "减小音量",
                style: TextStyle(),
              ),
              onPressed: () {
                _volume -= 0.3;
                if (_volume == 0) {
                  _volume = 0;
                }
                audioPlayerManager.setVolume(_volume);
              },
            ),
            //快进
            RaisedButton(
              child: Text(
                "快进",
                style: TextStyle(),
              ),
              onPressed: () {
                milliseconds += 5000;
                if (milliseconds == total) {
                  milliseconds = total;
                }
                audioPlayerManager.jump(milliseconds);
              },
            ),
            //快退
            RaisedButton(
              child: Text(
                "快退",
                style: TextStyle(),
              ),
              onPressed: () {
                milliseconds -= 5000;
                if (milliseconds == 0) {
                  milliseconds = 0;
                }
                audioPlayerManager.jump(milliseconds);
              },
            ),
            //下一个
            RaisedButton(
              child: Text(
                "下一个",
                style: TextStyle(),
              ),
              onPressed: () {
                _index += 1;
                if (_index == _musicList.length) {
                  _index = 0;
                }
                audioPlayerManager.playAsset(_musicList[_index]);
                _isPause = false;
                setState(() {});
              },
            ),
            //上一个
            RaisedButton(
              child: Text(
                "上一个",
                style: TextStyle(),
              ),
              onPressed: () {
                _index -= 1;
                if (_index == -1) {
                  _index = _musicList.length - 1;
                }

                audioPlayerManager.playAsset(_musicList[_index]);
                _isPause = false;
                setState(() {});
              },
            ),
          ],
        ),
      ),
    );
  }

  //以下为事件...

  ///监听播放进度位置
  _listenAudioPositionChanged() {
    //progress.inMilliseconds 当前进度
    audioPlayerManager.audioPlayer.onAudioPositionChanged
        .listen((progress) async {
      print("监听播放进度: ${progress.inMilliseconds}");
    });
  }

  ///监听播放器当前状态
  _listenAudioPlayerStateController() {
    //iOS
    // if (Platform.isIOS) {
    audioPlayerManager.audioPlayer.onNotificationPlayerStateChanged
        .listen((value) {
      print("isIOS监听播放: $value");
      _state = value;
      _nextPlayer();
    });
    // }
    //android
    // if (Platform.isAndroid) {
    audioPlayerManager.audioPlayer.onPlayerStateChanged.listen((value) {
      print("isAndroid监听播放: $value");
      _state = value;
      _nextPlayer();
    });
    // }
  }

  ///播放下一个
  _nextPlayer() {
    //是否播放完毕
    if (_state == AudioPlayerState.COMPLETED) {
      _index += 1;
      if (_index == _musicList.length) {
        _index = 0;
      }
      audioPlayerManager.playAsset(_musicList[_index]);
      _isPause = false;
      setState(() {});
    }
  }
}

三.目录结构

截屏2021-05-07 18.05.04.png 截屏2021-05-07 18.05.18.png 截屏2021-05-11 09.45.54.png

相关文章

  • 音频|音频测试!

    先上传一个音频。试试效果。

  • 音频开发 -- 音频基础

    一、音频播放流程 音乐播放器在播放音频时的流程:1.读入音频文件,使用解码器将各种格式的音频文件解压,还原为原始的...

  • 音频 初识音频功能

    简介: Unity 作为一款主打游戏功能的引擎,声音也是必不可少的,在录制视频的时候我们可能希望直接将视频录制下来...

  • 音频

    首先在音频平台上注册有一个帐号,等帐号注册好了,可以在上面录音,因为在初期阶段,所以,可以首先选择自己喜欢的...

  • 音频

  • 音频

    audio标签:autoplay 自动播放controls 显示控件l...

  • 音频

    1.苹果有以下两种常见录音方式: (1)苹果推荐我们使用AVFoundation框架中的AVAudioPlayer...

  • 音频

    今天11:30分起床,看了专栏… 在听音频时妈妈也要听就给她听了。 决定了每天抽时间做不擅长的事,应该对成长极其有用处。

  • 音频

    iOS和安卓同时做音频的时候,最好用wav的,现在只试过这个

  • 音频

    原文链接:http://www.cnblogs.com/YanPengBlog/p/5266783.html

网友评论

    本文标题:9.1.flutter-音频

    本文链接:https://www.haomeiwen.com/subject/bfbzbktx.html