使用第三方插件實(shí)現(xiàn)音頻播放,支持安卓、IOS
先上官網(wǎng)鏈接:
https://pub.dev/packages/audioplayers
安裝
根目錄打開(kāi) pubspec.yaml 找到dependencies, 添加
audioplayers: ^0.13.1
控制臺(tái):(有些編輯器會(huì)自動(dòng)幫你安裝)
flutter pub get
使用
引用
import 'package:audioplayers/audioplayers.dart';
初始化
AudioPlayer audioPlayer = AudioPlayer();
播放
play() async {
int result = await audioPlayer.play(xxx.mp3);
if (result == 1) {
// success
print('play success');
} else {
print('play failed');
}
}
暫停
pause() async {
int result = await audioPlayer.pause();
if (result == 1) {
// success
print('pause success');
} else {
print('pause failed');
}
}
轉(zhuǎn)跳
int result = await audioPlayer.seek(new Duration(milliseconds: startMilliseconds));
if (result == 1) {
print('go to success');
// await audioPlayer.resume();
} else {
print('go to failed');
}
播放中監(jiān)聽(tīng)
audioPlayer.onAudioPositionChanged.listen((p) async {
// p參數(shù)可以獲取當(dāng)前進(jìn)度,也是可以調(diào)整的,比如p.inMilliseconds
})
milliseconds參數(shù)可以調(diào)整的,請(qǐng)注意這個(gè)部分,不然發(fā)現(xiàn)一轉(zhuǎn)頭就沒(méi)聲音,要設(shè)置好哦。
一般我只用到這些,更多請(qǐng)看官網(wǎng)。
離開(kāi)的時(shí)候,釋放資源
例子
@override
void deactivate() async{
print('結(jié)束');
int result = await audioPlayer.release();
if (result == 1) {
print('release success');
} else {
print('release failed');
}
super.deactivate();
}
這時(shí)候釋放資源了,作者是這樣說(shuō)的
Releases the resources associated with this media player.
The resources are going to be fetched or buffered again as soon as you call [play] [setUrl]
其實(shí)除了這個(gè),還有一個(gè)dispose方法,用法一樣,只是返回的不是int,而是void,只是我在使用的時(shí)候,報(bào)錯(cuò)了。。 具體大家可以再研究下。語(yǔ)法:
Future<void> dispose ()
恢復(fù)播放
resume → Future<int> 和上面用法一樣用法。
作者描述原文:
Resumes the audio that has been paused or stopped, just like calling play, but without changing the parameters.
上面說(shuō)恢復(fù)剛剛暫?;蛘咄V共シ诺囊纛l,問(wèn)題來(lái)了,暫停和播放有啥區(qū)別?歡迎下方評(píng)論留言。
音量控制
Future<int> setVolume (
double volume
)
也是Future函數(shù),返回int類型,和上面一致,然后傳入音量的值,取區(qū)域是 0 - 1。
TIPS
請(qǐng)不要在build函數(shù)里面聲明變量。在initState中初始化,參考:
@override
void initState() {
super.initState();
initAudioPlayer();
}
void initAudioPlayer() {
audioPlayer = new AudioPlayer();
_positionSubscription =
audioPlayer.onAudioPositionChanged.listen((p) async {
if (!pickItem.containsKey('end')) {
return;
}
...
flutter pub get
的時(shí)候
如果你遇到了如下錯(cuò)誤
"flutter run" prints warning multiple times after switching Flutter SDK's
請(qǐng)運(yùn)行如下命令
flutter packages upgrade
如果你運(yùn)行這個(gè)的時(shí)候出現(xiàn)
Waiting for another flutter command to release the startup lock
請(qǐng)切換到flutter安裝目錄下,運(yùn)行
rm ./bin/cache/lockfile
然后再次執(zhí)行
flutter packages upgrade
問(wèn)題將解決。
相關(guān)鏈接
https://pub.dev/documentation/audioplayers/latest/audioplayers/AudioPlayer-class.html
--END--