当前位置: 首页 > news >正文

flutter开发实战-just_audio实现播放音频暂停音频设置音量等

flutter开发实战-just_audio实现播放音频暂停音频设置音量等

最近开发过程中遇到需要播放背景音等音频播放,这里使用just_audio来实现播放音频暂停音频设置音量等

在这里插入图片描述

一、引入just_audio

在pubspec.yaml引入just_audio

  just_audio: ^2.7.0

在iOS上,video_player使用的是AVPlayer进行播放。
在Android上,video_player使用的是ExoPlayer。

二、使用前设置

2.1 在iOS中的设置
在iOS工程中info.plist添加一下设置,以便支持Https,HTTP的视频地址

<key>NSAppTransportSecurity</key>
<dict><key>NSAllowsArbitraryLoads</key><true/>
</dict>

2.2 在Android中的设置
需要在/android/app/src/main/AndroidManifest.xml文件中添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

三、just_audio实现播放音频暂停音频设置音量等

引入just_audio后,可以使用AudioPlayer来播放音频

3.1 常用操作如下

  • 播放
await _audioPlayer.play();
  • 暂停
await _audioPlayer.pause();
  • seek
await _audioPlayer.seek(position);
  • 停止
await _audioPlayer.pause();
await _audioPlayer.seek(Duration.zero);
  • 设置音量
await _audioPlayer.setVolume(volume);

3.2 使用just_audio实现播放player

这里通过player来获取SDAudioPlayerState状态,控制音频的暂停音频设置音量等操作

import 'package:flutter_app/manager/logger_manager.dart';
import 'package:just_audio/just_audio.dart';// 播放回调
typedef SDAudioPlayerCallBack = void Function(SDAudioPlayerState state, SDAudioPlayerError? error);// 播放音频的状态
enum SDAudioPlayerState {idle, // 默认loading, // 加载中buffering, // 缓存中ready, // 可播放completed, // 播放完成
}// 播放音频出现错误
class SDAudioPlayerError {String? message;
}// 定义优先级的类
class SDMusicConfig {// 音频文件地址late String audioUrl = '';late bool runLoop = false; // 是否循环播放// 构造函数SDMusicConfig(this.audioUrl, this.audioPriority, this.runLoop);
}// 播放音频文件
class SDMusicPlayer {// 音频播放late AudioPlayer _audioPlayer;// 优先级late SDMusicConfig _musicConfig;late bool _playing = false; // 是否正在播放late SDAudioPlayerState _playerState = SDAudioPlayerState.idle; // 状态late SDAudioPlayerCallBack? _playerCallBack;SDMusicPlayer(this._audioPlayer, this._musicConfig){setAudioUrl(this._musicConfig.audioUrl);openPlayCallBack((state, error) {});}SDMusicConfig getMusicConfig() {return _musicConfig;}void openPlayCallBack(SDAudioPlayerCallBack playerCallBack) {_playerCallBack = playerCallBack;_audioPlayer.playerStateStream.listen((state) {_playing = state.playing;switch(state.processingState) {case ProcessingState.idle: {_playerState = SDAudioPlayerState.idle;break;}case ProcessingState.loading: {_playerState = SDAudioPlayerState.loading;break;}case ProcessingState.buffering: {_playerState = SDAudioPlayerState.buffering;break;}case ProcessingState.ready: {_playerState = SDAudioPlayerState.ready;break;}case ProcessingState.completed: {_playerState = SDAudioPlayerState.completed;if (_musicConfig.runLoop == true) {// 循环播放的时候seek(Duration.zero);play();} else {stop();}break;}default:}if (_playerCallBack != null) {_playerCallBack!(_playerState, null);}});}// var duration = await player.setUrl('https://foo.com/bar.mp3');Future<void> setAudioUrl(String url) async {SDAudioPlayerError? error;if (url.isNotEmpty) {// Set the audio source but manually load audio at a later point.try {_audioPlayer.setUrl(url, preload: true);// Acquire platform decoders and start loading audio.var duration = await _audioPlayer.load();print("url:${url} duration:${duration}");} on PlayerException catch (e) {// iOS/macOS: maps to NSError.code// Android: maps to ExoPlayerException.type// Web: maps to MediaError.code// Linux/Windows: maps to PlayerErrorCode.indexprint("SDAudioPlayer Error code: ${e.code}");// iOS/macOS: maps to NSError.localizedDescription// Android: maps to ExoPlaybackException.getMessage()// Web/Linux: a generic message// Windows: MediaPlayerError.messageprint("SDAudioPlayer Error message: ${e.message}");error = SDAudioPlayerError();error.message = e.message;} on PlayerInterruptedException catch (e) {// This call was interrupted since another audio source was loaded or the// player was stopped or disposed before this audio source could complete// loading.LoggerManager().debug("SDAudioPlayer Connection aborted: ${e.message}");error = SDAudioPlayerError();error.message = e.message;} catch (e) {// Fallback for all errorsprint("e: ${e}");error = SDAudioPlayerError();error.message = e.toString();}} else {error = SDAudioPlayerError();error.message = '播放地址不能为空';}if (_playerCallBack != null) {_playerCallBack!(_playerState, error);}}void play() async {// Usually you don't want to wait for playback to finish.if (_musicConfig.audioUrl != null && _musicConfig.audioUrl.isNotEmpty) {if (_playing == false) {// 正在播放await _audioPlayer.play();}}}void pause() async {if (_musicConfig.audioUrl != null && _musicConfig.audioUrl.isNotEmpty) {await _audioPlayer.pause();}}void stop() async {if (_musicConfig.audioUrl != null && _musicConfig.audioUrl.isNotEmpty) {await _audioPlayer.pause();await _audioPlayer.seek(Duration.zero);}}void seek(Duration position) async {if (_musicConfig.audioUrl != null && _musicConfig.audioUrl.isNotEmpty) {await _audioPlayer.seek(position);}}void setVolume(double volume) async {if (_musicConfig.audioUrl != null && _musicConfig.audioUrl.isNotEmpty) {await _audioPlayer.setVolume(volume);}}// 不需要该播放器,则需要调用该方法void dispose() async {await _audioPlayer.dispose();}
}

四、小结

flutter开发实战-just_audio实现播放音频暂停音频设置音量等。
学习记录,每天不停进步。

相关文章:

flutter开发实战-just_audio实现播放音频暂停音频设置音量等

flutter开发实战-just_audio实现播放音频暂停音频设置音量等 最近开发过程中遇到需要播放背景音等音频播放&#xff0c;这里使用just_audio来实现播放音频暂停音频设置音量等 一、引入just_audio 在pubspec.yaml引入just_audio just_audio: ^2.7.0在iOS上&#xff0c;video_p…...

【Bert101】最先进的 NLP 模型解释【01/4】

0 什么是伯特&#xff1f; BERT是来自【Bidirectional Encoder Representations from Transformers】变压器的双向编码器表示的缩写&#xff0c;是用于自然语言处理的机器学习&#xff08;ML&#xff09;模型。它由Google AI Language的研究人员于2018年开发&#xff0c;可作为…...

c语言经典例题讲解(输出菱形,喝汽水问题)

目录 一、输出菱形 二、喝汽水问题 方法1&#xff1a;一步一步来 方法二&#xff1a;直接套公式 一、输出菱形 输出类似于下图的菱形&#xff1a; 通过分析&#xff1a;1、先分为上下两部分输出 2.在输出前先输出空格 3.找规律进行输出 可知&#xff0c;可令上半部分lin…...

【Flutter】【基础】CustomPaint 绘画功能(一)

功能&#xff1a;CustomPaint 相当于在一个画布上面画画&#xff0c;可以自己绘制不同的颜色形状等 在各种widget 或者是插件不能满足到需求的时候&#xff0c;可以自己定义一些形状 使用实例和代码&#xff1a; CustomPaint&#xff1a; 能使你绘制的东西显示在你的ui 上面&a…...

iOS 实现图片高斯模糊效果

效果图 用到了 UIVisualEffectView 实现代码 - (UIVisualEffectView *)bgEffectView{if(!_bgEffectView){UIBlurEffect *blur [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];_bgEffectView [[UIVisualEffectView alloc] initWithEffect:blur];}return _bgEffect…...

[保研/考研机试] KY7 质因数的个数 清华大学复试上机题 C++实现

描述 求正整数N(N>1)的质因数的个数。 相同的质因数需要重复计算。如1202*2*2*3*5&#xff0c;共有5个质因数。 输入描述&#xff1a; 可能有多组测试数据&#xff0c;每组测试数据的输入是一个正整数N&#xff0c;(1<N<10^9)。 输出描述&#xff1a; 对于每组数…...

初识Redis

目录 认识Redis分布式系统Redis的特性Redis的应用场景Redis客户端Redis命令 认识Redis 上面一段话是官网给出的对Redis的介绍&#xff0c;in-memory data store表明Redis是在内存中存储数据的&#xff0c;这和我们接触的其他数据库就有很大的不同&#xff0c;比如MySQL&#xf…...

每天一道leetcode:115. 不同的子序列(动态规划困难)

今日份题目&#xff1a; 给你两个字符串 s 和 t &#xff0c;统计并返回在 s 的 子序列 中 t 出现的个数。 题目数据保证答案符合 32 位带符号整数范围。 示例1 输入&#xff1a;s "rabbbit", t "rabbit" 输出&#xff1a;3 解释&#xff1a; 如下所…...

服务器数据恢复-RAID5多块磁盘离线导致崩溃的数据恢复案例

服务器数据恢复环境&#xff1a; DELL POWEREDGE某型号服务器中有一组由6块SCSI硬盘组建的RAID5阵列&#xff0c;LINUX REDHAT操作系统&#xff0c;EXT3文件系统&#xff0c;存放图片文件。 服务器故障&分析&#xff1a; 服务器raid5阵列中有一块硬盘离线&#xff0c;管理员…...

NO.2 MyBatis框架:创建Mapper接口和映射文件,实现基本增删改查

目录 1、Mapper接口和映射文件关系 2、Mapper接口和映射文件的命名规则 2.1 Mapper接口的命名规则 2.2 映射文件的命名规则 3、Mapper接口和映射文件的创建及增删改查的实现 3.1 Mapper接口和映射文件的创建 3.2 增删改查的实现 3.2.1表结构 3.2.2 创建表User对应的实…...

【JS】怎么提取object类的内容

需求&#xff1a;在网页端中通过getElementsByClassName获取到一个元素&#xff0c;想提取其中的数字内容做个if判断&#xff0c;奈何一直提取不了 开始获取元素时&#xff0c;以为默认就是字符类型&#xff1b;但使用操作字符的函数就失败&#xff0c;然后就考虑数据类型是不是…...

分布式系统的 38 个知识点

天天说分布式分布式&#xff0c;那么我们是否知道什么是分布式&#xff0c;分布式会遇到什么问题&#xff0c;有哪些理论支撑&#xff0c;有哪些经典的应对方案&#xff0c;业界是如何设计并保证分布式系统的高可用呢&#xff1f; 1. 架构设计 这一节将从一些经典的开源系统架…...

机器学习基础(二)

线性回归 误差是独立并且具有相同的分布通常认为服从均值为0方差为的高斯分布。 损失函数(loss Function)/代价函数(Cost Function) 其实两种叫法都可以,损失函数(loss function)或代价函数(cost function)是将随机事件或其有关随机变量的取值映射为非负实数以表示该随…...

Java 实现Rtsp 转rtmp,hls,flv

服务支撑&#xff1a;FFmpeg srs(流媒体服务器) 整个流程是 FFmpeg 收流转码 推 rtmp 到流媒体服务 流媒体服务再 分发流到公网 搭建流媒体服务: 1. SRS (Simple Realtime Server) | SRS &#xff08;本例子使用的是SrS 安装使用docker &#xff09; 2.GitHub - ZLMedi…...

机器学习基础(三)

逻辑回归 场景 垃圾邮件分类 预测肿瘤是良性还是恶性 预测某人的信用是否良好 正确率与召回率 正确率与召回率(Precision & Recall)是广泛应用于信息检索和统计学分类领域的两个度量值,用来评价结果的质量。 一般来说,正确率就是检索出来的条目有多少是正确的,召回率就…...

Kubeadm安装K8s集群

一、硬件环境 准备3台Linux服务器&#xff0c;此处用Vmware虚拟机。 主机名CPU内存k8smaster2核4Gk8snode12核4Gk8snode22核4G 二、系统前置准备 配置三台主机的hosts文件 cat << EOF > /etc/hosts 192.168.240.130 k8smaster 192.168.240.132 k8snode1 192.168.…...

【C++】开源:spdlog跨平台日志库配置使用

&#x1f60f;★,:.☆(&#xffe3;▽&#xffe3;)/$:.★ &#x1f60f; 这篇文章主要介绍spdlog日志库配置使用。 无专精则不能成&#xff0c;无涉猎则不能通。——梁启超 欢迎来到我的博客&#xff0c;一起学习&#xff0c;共同进步。 喜欢的朋友可以关注一下&#xff0c;下…...

[Azkaban] No active executors found

没有找到活动的executors&#xff0c;需在MySQL数据库里设置端口为12321的executors表的active为1&#xff1a; select * from executors;如果显示active0 则需要进行处理&#xff1a; update azkaban.executors set active1;当active0&#xff0c;更新为1时&#xff0c;用 n…...

无涯教程-Perl - recv函数

描述 This function receives a message on SOCKET attempting to read LENGTH bytes, placing the data read into variable SCALAR.The FLAGS argument takes the same values as the recvfrom( ) system function, on which the function is based. When communicating wit…...

算法练习-搜索 相关

文章目录 迷宫问题 迷宫问题 定义一个二维数组 m行 * n列 &#xff0c;如 4 5 数组下所示&#xff1a; int arr[5][5] { 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, }; 它表示一个迷宫&#xff0c;1表示墙壁&#xff0c;0表示可以走的路&#xff0c;只…...

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…...

k8s从入门到放弃之Ingress七层负载

k8s从入门到放弃之Ingress七层负载 在Kubernetes&#xff08;简称K8s&#xff09;中&#xff0c;Ingress是一个API对象&#xff0c;它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress&#xff0c;你可…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…...

AI编程--插件对比分析:CodeRider、GitHub Copilot及其他

AI编程插件对比分析&#xff1a;CodeRider、GitHub Copilot及其他 随着人工智能技术的快速发展&#xff0c;AI编程插件已成为提升开发者生产力的重要工具。CodeRider和GitHub Copilot作为市场上的领先者&#xff0c;分别以其独特的特性和生态系统吸引了大量开发者。本文将从功…...

selenium学习实战【Python爬虫】

selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

Python Einops库:深度学习中的张量操作革命

Einops&#xff08;爱因斯坦操作库&#xff09;就像给张量操作戴上了一副"语义眼镜"——让你用人类能理解的方式告诉计算机如何操作多维数组。这个基于爱因斯坦求和约定的库&#xff0c;用类似自然语言的表达式替代了晦涩的API调用&#xff0c;彻底改变了深度学习工程…...

打手机检测算法AI智能分析网关V4守护公共/工业/医疗等多场景安全应用

一、方案背景​ 在现代生产与生活场景中&#xff0c;如工厂高危作业区、医院手术室、公共场景等&#xff0c;人员违规打手机的行为潜藏着巨大风险。传统依靠人工巡查的监管方式&#xff0c;存在效率低、覆盖面不足、判断主观性强等问题&#xff0c;难以满足对人员打手机行为精…...

MySQL 主从同步异常处理

阅读原文&#xff1a;https://www.xiaozaoshu.top/articles/mysql-m-s-update-pk MySQL 做双主&#xff0c;遇到的这个错误&#xff1a; Could not execute Update_rows event on table ... Error_code: 1032是 MySQL 主从复制时的经典错误之一&#xff0c;通常表示&#xff…...