volume_controlを利用して、下記のようなUIを作成し実際にiOSの音量を調整できるようにしてみました。
pubspec.yaml
dependencies:
volume_control: ^X.X.X
バージョンは上記サイトより指定し
flutter pub get
import 'package:volume_control/volume_control.dart';
して使えるようにします。とりあえず、Example
通りにやっても動かなかったので、Hooks
に切り替えましたが上手くスライドしてくれず。
dependencies:
hooks_riverpod: ^1.0.4
flutter_hooks: ^0.18.5+1
riverpod
のHookConsumerWidget
の中でuseState
で呼んであげることで解決致しました。
volume.dart
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:volume_control/volume_control.dart';
class SoundControl extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final volumeValue = useState(0.5);
Timer? timer;
return Scaffold(
backgroundColor: Colors.grey.shade200,
body: Column(
children: [
Container(
child: SafeArea(
child: Column(
children: [
Container(
height: 65,
child: Card(
child: Column(
children: [
ListTile(
leading: Container(
child: Icon(
Icons.volume_mute,
size: 30,
),
),
title: CupertinoSlider(
value: volumeValue.value,
min: 0,
max: 1,
divisions: 100,
onChanged: (val) {
volumeValue.value = val;
if (timer != null) {
timer?.cancel();
}
timer =
Timer(Duration(milliseconds: 200), () {
VolumeControl.setVolume(val);
});
print("val:$val");
}),
trailing: Icon(Icons.volume_up, size: 30),
),
],
),
),
),
],
),
),
),
],
),
);
}
}
スライダーのUI
はCupertino
をインポートしてiOS
スタイルにしてあります。SoundControl()
を使用し、シュミレータで動かしてみると、デバッグコンソールに下記ログが流れてコントロールできるようになります。