Flutter播放音频插件 just_audio的使用基本方法

发布于 2022-07-19  92 次阅读


本文章使用的Flutter版本为2.5.0,由于我只了解了安卓系统的用法,所以这里暂时只介绍安卓端的just_audio的插件使用,另外有些功能我没用过,为避免在这里就先暂时不讲了。

添加插件

pubspec.yml添加插件。

just_audio: ^0.9.24

获取音频资源

import 'package:just_audio/just_audio.dart';
AudioPlay(){
  AudioPlayer player = AudioPlayer(); //创建播放器
  player.setUrl('https://foo.com/bar.mp3'); //通过url获取资源
  player.setAssets('lib/assets/audios/1.mp3'); //通过assets加载
  player.setFilePath('documents/xxx/xxx.mp3'); //通过文件路径加载
  player.play(); //播放音频
}

基础操作

import 'package:just_audio/just_audio.dart';
AudioPlay() async{
  final player = AudioPlayer();                   
  final duration = await player.setUrl(
'https://foo.com/bar.mp3');
  player.play(); //播放
  await player.play(); //当其他播放器播放完毕后播放音频                          
  await player.pause(); //暂停
  await player.seek(Duration(second: 10)); //跳转到十秒钟的位置
  await player.setSpeed(2.0); //设置播放速度(2倍速)
  await player.setVolume(0.5); //设置音量(0.5为最大音量的一班)
  await player.stop(); //停止播放并释放资源
}

多个播放器播放

import 'package:just_audio/just_audio.dart';

AudioPlay() async{
  AudioPlayer player1 = AudioPlayer(); //创建播放器
  AudioPlayer player2 = AudioPlayer(); //创建播放器

  player1.setUrl('https://foo.com/bar.mp3'); //通过url获取资源
  player2.setUrl('https://foo.com/bar.mp3'); //通过url获取资源

  player1.play(); //播放
  player2.play(); //player1播放时player2与player1同时播放
  await player.play(); //直到player1播放完毕后player2播放

  player1.pause() //暂停
  player2.pause();

  await player1.stop(); //释放每个播放器的音频解码与缓存(你可以理解为释放资源)
  await player2.stop();
}

在指定片段播放

//播放2-4秒的片段然后再播放10-12秒的片段
await player.setClip(start: Duration(seconds: 2), end: Duration(seconds: 4));
await player.play(); await player.pause();
await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 12));
await player.play(); await player.pause();

await player.setClip(); //清除片段设置

播放列表

//定义播放列表
final playlist = ConcatenatingAudioSource(
  //再播放完音频前是否加载下一个音频
  useLazyPreparation: true,
  //自定义随机播放算法
  shuffleOrder: DefaultShuffleOrder(),
  //指定播放列表
  children: [
    AudioSource.uri(Uri.parse('https://example.com/track1.mp3')),
    AudioSource.uri(Uri.parse('https://example.com/track2.mp3')),
    AudioSource.uri(Uri.parse('https://example.com/track3.mp3')),
  ],
);

//加载并播放列表
await player.setAudioSource(playlist, initialIndex: 0, initialPosition: Duration.zero);
await player.seekToNext();                     //跳至下一个音频
await player.seekToPrevious();                 //跳至上一个音频
await player.seek(Duration.zero, index: 2);    //调至列表第二个音频,从0秒开始播放
await player.setLoopMode(LoopMode.all);        //设置循环播放模式(off|all|one)
await player.setShuffleModeEnabled(true);      //设置随机播放(true|false)

//更新播放列表
await playlist.add(newChild1);
await playlist.insert(3, newChild2);
await playlist.removeAt(3);

使用音频缓存

//清除缓存列表
await AudioPlayer.clearAssetCache();

//下载并缓存音频
final audioSource = LockCachingAudioSource('https://foo.com/bar.mp3');
await player.setAudioSource(audioSource);
//删除缓存文件
await audioSource.clearCache();

调试播放器

//在加载、播放时进行调试
try {
  await player.setUrl("https://s3.amazonaws.com/404-file.mp3");
} 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.index
  print("Error code: ${e.code}");
  // iOS/macOS: maps to NSError.localizedDescription
  // Android: maps to ExoPlaybackException.getMessage()
  // Web/Linux: a generic message
  // Windows: MediaPlayerError.message
  print("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.
  print("Connection aborted: ${e.message}");
} catch (e) {
  // Fallback for all other errors
  print('An error occured: $e');
}

//报错时回滚播放
player.playbackEventStream.listen((event) {}, onError: (Object e, StackTrace st) {
  if (e is PlayerException) {
    print('Error code: ${e.code}');
    print('Error message: ${e.message}');
  } else {
    print('An error occurred: $e');
  }
});

谢谢你能看完呀~~~