flet-audio 0.0.1__py3-none-any.whl → 0.1.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of flet-audio might be problematic. Click here for more details.

flet_audio/__init__.py CHANGED
@@ -1 +1,7 @@
1
-
1
+ from flet_audio.audio import (
2
+ Audio,
3
+ AudioDurationChangeEvent,
4
+ AudioPositionChangeEvent,
5
+ AudioState,
6
+ AudioStateChangeEvent,
7
+ )
flet_audio/audio.py ADDED
@@ -0,0 +1,294 @@
1
+ from enum import Enum
2
+ from typing import Any, Optional
3
+
4
+ from flet.core.control import Control, OptionalNumber
5
+ from flet.core.control_event import ControlEvent
6
+ from flet.core.event_handler import EventHandler
7
+ from flet.core.ref import Ref
8
+ from flet.core.types import OptionalControlEventCallable, OptionalEventCallable
9
+ from flet.utils import deprecated
10
+
11
+
12
+ class ReleaseMode(Enum):
13
+ RELEASE = "release"
14
+ LOOP = "loop"
15
+ STOP = "stop"
16
+
17
+
18
+ class AudioState(Enum):
19
+ STOPPED = "stopped"
20
+ PLAYING = "playing"
21
+ PAUSED = "paused"
22
+ COMPLETED = "completed"
23
+ DISPOSED = "disposed"
24
+
25
+
26
+ class AudioStateChangeEvent(ControlEvent):
27
+ def __init__(self, e: ControlEvent):
28
+ super().__init__(e.target, e.name, e.data, e.control, e.page)
29
+ self.state: AudioState = AudioState(e.data)
30
+
31
+
32
+ class AudioPositionChangeEvent(ControlEvent):
33
+ def __init__(self, e: ControlEvent):
34
+ super().__init__(e.target, e.name, e.data, e.control, e.page)
35
+ self.position: int = int(e.data)
36
+
37
+
38
+ class AudioDurationChangeEvent(ControlEvent):
39
+ def __init__(self, e: ControlEvent):
40
+ super().__init__(e.target, e.name, e.data, e.control, e.page)
41
+ self.duration: int = int(e.data)
42
+
43
+
44
+ class Audio(Control):
45
+ """
46
+ A control to simultaneously play multiple audio files. Works on macOS, Linux, Windows, iOS, Android and web. Based on audioplayers Flutter widget (https://pub.dev/packages/audioplayers).
47
+
48
+ Audio control is non-visual and should be added to `page.overlay` list.
49
+
50
+ Example:
51
+ ```
52
+ import flet as ft
53
+
54
+ import flet_audio as fta
55
+
56
+ def main(page: ft.Page):
57
+ audio1 = fta.Audio(
58
+ src="https://luan.xyz/files/audio/ambient_c_motion.mp3", autoplay=True
59
+ )
60
+ page.overlay.append(audio1)
61
+ page.add(
62
+ ft.Text("This is an app with background audio."),
63
+ ft.ElevatedButton("Stop playing", on_click=lambda _: audio1.pause()),
64
+ )
65
+
66
+ ft.app(target=main)
67
+ ```
68
+
69
+ -----
70
+
71
+ Online docs: https://flet.dev/docs/controls/audio
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ src: Optional[str] = None,
77
+ src_base64: Optional[str] = None,
78
+ autoplay: Optional[bool] = None,
79
+ volume: OptionalNumber = None,
80
+ balance: OptionalNumber = None,
81
+ playback_rate: OptionalNumber = None,
82
+ release_mode: Optional[ReleaseMode] = None,
83
+ on_loaded: OptionalControlEventCallable = None,
84
+ on_duration_changed: OptionalEventCallable[AudioDurationChangeEvent] = None,
85
+ on_state_changed: OptionalEventCallable[AudioStateChangeEvent] = None,
86
+ on_position_changed: OptionalEventCallable[AudioPositionChangeEvent] = None,
87
+ on_seek_complete: OptionalControlEventCallable = None,
88
+ #
89
+ # Control
90
+ #
91
+ ref: Optional[Ref] = None,
92
+ data: Any = None,
93
+ ):
94
+ Control.__init__(
95
+ self,
96
+ ref=ref,
97
+ data=data,
98
+ )
99
+
100
+ self.__on_state_changed = EventHandler(lambda e: AudioStateChangeEvent(e))
101
+ self._add_event_handler("state_changed", self.__on_state_changed.get_handler())
102
+
103
+ self.__on_position_changed = EventHandler(lambda e: AudioPositionChangeEvent(e))
104
+ self._add_event_handler(
105
+ "position_changed", self.__on_position_changed.get_handler()
106
+ )
107
+
108
+ self.__on_duration_changed = EventHandler(lambda e: AudioDurationChangeEvent(e))
109
+ self._add_event_handler(
110
+ "duration_changed", self.__on_duration_changed.get_handler()
111
+ )
112
+
113
+ self.src = src
114
+ self.src_base64 = src_base64
115
+ self.autoplay = autoplay
116
+ self.volume = volume
117
+ self.balance = balance
118
+ self.playback_rate = playback_rate
119
+ self.release_mode = release_mode
120
+ self.on_loaded = on_loaded
121
+ self.on_duration_changed = on_duration_changed
122
+ self.on_state_changed = on_state_changed
123
+ self.on_position_changed = on_position_changed
124
+ self.on_seek_complete = on_seek_complete
125
+
126
+ def _get_control_name(self):
127
+ return "audio"
128
+
129
+ def play(self):
130
+ self.invoke_method("play")
131
+
132
+ def pause(self):
133
+ self.invoke_method("pause")
134
+
135
+ def resume(self):
136
+ self.invoke_method("resume")
137
+
138
+ def release(self):
139
+ self.invoke_method("release")
140
+
141
+ def seek(self, position_milliseconds: int):
142
+ self.invoke_method("seek", {"position": str(position_milliseconds)})
143
+
144
+ def get_duration(self, wait_timeout: Optional[float] = 5) -> Optional[int]:
145
+ sr = self.invoke_method(
146
+ "get_duration",
147
+ wait_for_result=True,
148
+ wait_timeout=wait_timeout,
149
+ )
150
+ return int(sr) if sr else None
151
+
152
+ async def get_duration_async(
153
+ self, wait_timeout: Optional[float] = 5
154
+ ) -> Optional[int]:
155
+ sr = await self.invoke_method_async(
156
+ "get_duration",
157
+ wait_for_result=True,
158
+ wait_timeout=wait_timeout,
159
+ )
160
+ return int(sr) if sr else None
161
+
162
+ def get_current_position(self, wait_timeout: Optional[float] = 5) -> Optional[int]:
163
+ sr = self.invoke_method(
164
+ "get_current_position",
165
+ wait_for_result=True,
166
+ wait_timeout=wait_timeout,
167
+ )
168
+ return int(sr) if sr else None
169
+
170
+ async def get_current_position_async(
171
+ self, wait_timeout: Optional[float] = 5
172
+ ) -> Optional[int]:
173
+ sr = await self.invoke_method_async(
174
+ "get_current_position",
175
+ wait_for_result=True,
176
+ wait_timeout=wait_timeout,
177
+ )
178
+ return int(sr) if sr else None
179
+
180
+ # src
181
+ @property
182
+ def src(self):
183
+ return self._get_attr("src")
184
+
185
+ @src.setter
186
+ def src(self, value):
187
+ self._set_attr("src", value)
188
+
189
+ # src_base64
190
+ @property
191
+ def src_base64(self):
192
+ return self._get_attr("srcBase64")
193
+
194
+ @src_base64.setter
195
+ def src_base64(self, value):
196
+ self._set_attr("srcBase64", value)
197
+
198
+ # autoplay
199
+ @property
200
+ def autoplay(self) -> bool:
201
+ return self._get_attr("autoplay", data_type="bool", def_value=False)
202
+
203
+ @autoplay.setter
204
+ def autoplay(self, value: Optional[bool]):
205
+ self._set_attr("autoplay", value)
206
+
207
+ # volume
208
+ @property
209
+ def volume(self) -> OptionalNumber:
210
+ return self._get_attr("volume")
211
+
212
+ @volume.setter
213
+ def volume(self, value: OptionalNumber):
214
+ if value is None or (0 <= value <= 1):
215
+ self._set_attr("volume", value)
216
+
217
+ # balance
218
+ @property
219
+ def balance(self) -> OptionalNumber:
220
+ return self._get_attr("balance")
221
+
222
+ @balance.setter
223
+ def balance(self, value: OptionalNumber):
224
+ if value is None or (-1 <= value <= 1):
225
+ self._set_attr("balance", value)
226
+
227
+ # playback_rate
228
+ @property
229
+ def playback_rate(self) -> OptionalNumber:
230
+ return self._get_attr("playbackRate")
231
+
232
+ @playback_rate.setter
233
+ def playback_rate(self, value: OptionalNumber):
234
+ if value is None or (0 <= value <= 2):
235
+ self._set_attr("playbackRate", value)
236
+
237
+ # release_mode
238
+ @property
239
+ def release_mode(self):
240
+ return self._get_attr("releaseMode")
241
+
242
+ @release_mode.setter
243
+ def release_mode(self, value: Optional[ReleaseMode]):
244
+ self._set_enum_attr("releaseMode", value, ReleaseMode)
245
+
246
+ # on_loaded
247
+ @property
248
+ def on_loaded(self):
249
+ return self._get_event_handler("loaded")
250
+
251
+ @on_loaded.setter
252
+ def on_loaded(self, handler: OptionalControlEventCallable):
253
+ self._add_event_handler("loaded", handler)
254
+
255
+ # on_duration_changed
256
+ @property
257
+ def on_duration_changed(self):
258
+ return self.__on_duration_changed.handler
259
+
260
+ @on_duration_changed.setter
261
+ def on_duration_changed(
262
+ self, handler: OptionalEventCallable[AudioDurationChangeEvent]
263
+ ):
264
+ self.__on_duration_changed.handler = handler
265
+
266
+ # on_state_changed
267
+ @property
268
+ def on_state_changed(self):
269
+ return self.__on_state_changed.handler
270
+
271
+ @on_state_changed.setter
272
+ def on_state_changed(self, handler: OptionalEventCallable[AudioStateChangeEvent]):
273
+ self.__on_state_changed.handler = handler
274
+
275
+ # on_position_changed
276
+ @property
277
+ def on_position_changed(self):
278
+ return self.__on_position_changed.handler
279
+
280
+ @on_position_changed.setter
281
+ def on_position_changed(
282
+ self, handler: OptionalEventCallable[AudioPositionChangeEvent]
283
+ ):
284
+ self.__on_position_changed.handler = handler
285
+ self._set_attr("onPositionChanged", True if handler is not None else None)
286
+
287
+ # on_seek_complete
288
+ @property
289
+ def on_seek_complete(self):
290
+ return self._get_event_handler("seek_complete")
291
+
292
+ @on_seek_complete.setter
293
+ def on_seek_complete(self, handler: OptionalControlEventCallable):
294
+ self._add_event_handler("seek_complete", handler)
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.2
2
+ Name: flet-audio
3
+ Version: 0.1.0.dev1
4
+ Summary: Audio control for Flet
5
+ Author-email: Flet contributors <hello@flet.dev>
6
+ Project-URL: Homepage, https://flet.dev
7
+ Project-URL: Documentation, https://flet.dev/docs/controls/audio
8
+ Project-URL: Repository, https://github.com/flet-dev/flet-audio
9
+ Project-URL: Issues, https://github.com/flet-dev/flet-audio/issues
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: flet>=0.25.1
14
+
15
+ # Flet Audio control
16
+
17
+ `Audio` control for Flet.
18
+
19
+ ## Usage
20
+
21
+ Add `flet-audio` as dependency (`pyproject.toml` or `requirements.txt`) to your Flet project.
22
+
23
+ ## Example
24
+
25
+ ```py
26
+
27
+ import flet as ft
28
+
29
+ import flet_audio as fta
30
+
31
+
32
+ def main(page: ft.Page):
33
+ audio1 = fta.Audio(
34
+ src="https://luan.xyz/files/audio/ambient_c_motion.mp3", autoplay=True
35
+ )
36
+ page.overlay.append(audio1)
37
+ page.add(
38
+ ft.Text("This is an app with background audio."),
39
+ ft.ElevatedButton("Stop playing", on_click=lambda _: audio1.pause()),
40
+ )
41
+
42
+ ft.app(main)
43
+ ```
@@ -0,0 +1,14 @@
1
+ flet_audio/__init__.py,sha256=06mfUVaDQEVi1LHKi-M0QC3dwANgKmOVOOKRx6JwWKI,147
2
+ flet_audio/audio.py,sha256=SJ15bKiDP7oDJhRg78CP1UAQhPNI7UZgDdWhj8aMbUw,8823
3
+ flutter/flet_audio/CHANGELOG.md,sha256=66sWepPaeTc9_lzcYIGU55AlxSU5Z1XVtknXpzd_-p8,40
4
+ flutter/flet_audio/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
5
+ flutter/flet_audio/README.md,sha256=BEITqZ4okarTGCquI4ii6tdffGm2qyxMkMZbsedCwLQ,60
6
+ flutter/flet_audio/analysis_options.yaml,sha256=32kjGAc-zF87inWaH5M46yGZWQDTwrwfvNLHeAocfG4,154
7
+ flutter/flet_audio/pubspec.yaml,sha256=7cPhnVgP-HwH12ZM21ZJD5YvFryebZ0k3f8HyVCie6Y,402
8
+ flutter/flet_audio/lib/flet_audio.dart,sha256=JH7ukuJeIBlZgn3VUvaGKC-MJdqTPNJLIeeo3E98qy0,93
9
+ flutter/flet_audio/lib/src/audio.dart,sha256=b4YNKucDyIkPoKS8aKXXU1X2wg2hCzRY3mNPcO4r0-s,8422
10
+ flutter/flet_audio/lib/src/create_control.dart,sha256=RtKBnV4KO8LIBDraM_QYZ03kz17HgVAEkjdnJPCj_EA,427
11
+ flet_audio-0.1.0.dev1.dist-info/METADATA,sha256=P8OPe8SXFWmOyJnEXfsd-lsyf-XR_KXW3QuDAa-HMf8,1090
12
+ flet_audio-0.1.0.dev1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
13
+ flet_audio-0.1.0.dev1.dist-info/top_level.txt,sha256=hZbGOXppSiKRUWJf1ZRlBKMyfijq6Y-8DffGOh10Wq4,19
14
+ flet_audio-0.1.0.dev1.dist-info/RECORD,,
@@ -1,4 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.9.0
2
+ Generator: setuptools (75.8.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ flet_audio
2
+ flutter
@@ -0,0 +1,3 @@
1
+ # 0.1.0
2
+
3
+ Initial release of the package.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ # Flet `Audio` control
2
+
3
+ `Audio` control to use in Flet apps.
@@ -0,0 +1,4 @@
1
+ include: package:flutter_lints/flutter.yaml
2
+
3
+ # Additional information about this file can be found at
4
+ # https://dart.dev/guides/language/analysis-options
@@ -0,0 +1,3 @@
1
+ library flet_audio;
2
+
3
+ export "src/create_control.dart" show createControl, ensureInitialized;
@@ -0,0 +1,246 @@
1
+ import 'dart:async';
2
+ import 'dart:convert';
3
+
4
+ import 'package:audioplayers/audioplayers.dart';
5
+ import 'package:collection/collection.dart';
6
+ import 'package:flet/flet.dart';
7
+ import 'package:flutter/foundation.dart';
8
+ import 'package:flutter/widgets.dart';
9
+
10
+ class AudioControl extends StatefulWidget {
11
+ final Control? parent;
12
+ final Control control;
13
+ final Widget? nextChild;
14
+ final FletControlBackend backend;
15
+
16
+ const AudioControl(
17
+ {super.key,
18
+ required this.parent,
19
+ required this.control,
20
+ required this.nextChild,
21
+ required this.backend});
22
+
23
+ @override
24
+ State<AudioControl> createState() => _AudioControlState();
25
+ }
26
+
27
+ class _AudioControlState extends State<AudioControl> with FletStoreMixin {
28
+ AudioPlayer? player;
29
+ void Function(Duration)? _onDurationChanged;
30
+ void Function(PlayerState)? _onStateChanged;
31
+ void Function(int)? _onPositionChanged;
32
+ Duration? _duration;
33
+ int _position = -1;
34
+ void Function()? _onSeekComplete;
35
+ StreamSubscription? _onDurationChangedSubscription;
36
+ StreamSubscription? _onStateChangedSubscription;
37
+ StreamSubscription? _onPositionChangedSubscription;
38
+ StreamSubscription? _onSeekCompleteSubscription;
39
+
40
+ @override
41
+ void initState() {
42
+ debugPrint("Audio.initState($hashCode)");
43
+ player = widget.control.state["player"];
44
+ if (player == null) {
45
+ player = AudioPlayer();
46
+ player = widget.control.state["player"] = player;
47
+ }
48
+ _onDurationChangedSubscription =
49
+ player?.onDurationChanged.listen((duration) {
50
+ _onDurationChanged?.call(duration);
51
+ _duration = duration;
52
+ });
53
+ _onStateChangedSubscription = player?.onPlayerStateChanged.listen((state) {
54
+ _onStateChanged?.call(state);
55
+ });
56
+ _onPositionChangedSubscription =
57
+ player?.onPositionChanged.listen((position) {
58
+ int posMs = (position.inMilliseconds / 1000).round() * 1000;
59
+ if (posMs != _position) {
60
+ _position = posMs;
61
+ } else if (position.inMilliseconds == _duration?.inMilliseconds) {
62
+ _position = _duration!.inMilliseconds;
63
+ } else {
64
+ return;
65
+ }
66
+ _onPositionChanged?.call(_position);
67
+ });
68
+ _onSeekCompleteSubscription = player?.onSeekComplete.listen((event) {
69
+ _onSeekComplete?.call();
70
+ });
71
+
72
+ widget.control.onRemove.clear();
73
+ widget.control.onRemove.add(_onRemove);
74
+ super.initState();
75
+ }
76
+
77
+ void _onRemove() {
78
+ debugPrint("Audio.remove($hashCode)");
79
+ widget.control.state["player"]?.dispose();
80
+ widget.backend.unsubscribeMethods(widget.control.id);
81
+ }
82
+
83
+ @override
84
+ void deactivate() {
85
+ debugPrint("Audio.deactivate($hashCode)");
86
+ _onDurationChangedSubscription?.cancel();
87
+ _onStateChangedSubscription?.cancel();
88
+ _onPositionChangedSubscription?.cancel();
89
+ _onSeekCompleteSubscription?.cancel();
90
+ super.deactivate();
91
+ }
92
+
93
+ @override
94
+ Widget build(BuildContext context) {
95
+ debugPrint(
96
+ "Audio build: ${widget.control.id} (${widget.control.hashCode})");
97
+
98
+ var src = widget.control.attrString("src", "")!;
99
+ var srcBase64 = widget.control.attrString("srcBase64", "")!;
100
+ if (src == "" && srcBase64 == "") {
101
+ return const ErrorControl(
102
+ "Audio must have either \"src\" or \"src_base64\" specified.");
103
+ }
104
+ bool autoplay = widget.control.attrBool("autoplay", false)!;
105
+ double? volume = widget.control.attrDouble("volume", null);
106
+ double? balance = widget.control.attrDouble("balance", null);
107
+ double? playbackRate = widget.control.attrDouble("playbackRate", null);
108
+ var releaseMode = ReleaseMode.values.firstWhereOrNull((e) =>
109
+ e.name.toLowerCase() ==
110
+ widget.control.attrString("releaseMode", "")!.toLowerCase());
111
+ bool onPositionChanged =
112
+ widget.control.attrBool("onPositionChanged", false)!;
113
+
114
+ final String prevSrc = widget.control.state["src"] ?? "";
115
+ final String prevSrcBase64 = widget.control.state["srcBase64"] ?? "";
116
+ final ReleaseMode? prevReleaseMode = widget.control.state["releaseMode"];
117
+ final double? prevVolume = widget.control.state["volume"];
118
+ final double? prevBalance = widget.control.state["balance"];
119
+ final double? prevPlaybackRate = widget.control.state["playbackRate"];
120
+
121
+ return withPageArgs((context, pageArgs) {
122
+ _onDurationChanged = (duration) {
123
+ widget.backend.triggerControlEvent(widget.control.id,
124
+ "duration_changed", duration.inMilliseconds.toString());
125
+ };
126
+
127
+ _onStateChanged = (state) {
128
+ debugPrint("Audio($hashCode) - state_changed: ${state.name}");
129
+ widget.backend.triggerControlEvent(
130
+ widget.control.id, "state_changed", state.name.toString());
131
+ };
132
+
133
+ if (onPositionChanged) {
134
+ _onPositionChanged = (position) {
135
+ widget.backend.triggerControlEvent(
136
+ widget.control.id, "position_changed", position.toString());
137
+ };
138
+ }
139
+
140
+ _onSeekComplete = () {
141
+ widget.backend.triggerControlEvent(widget.control.id, "seek_complete");
142
+ };
143
+
144
+ () async {
145
+ debugPrint("Audio ($hashCode) src=$src, prevSrc=$prevSrc");
146
+ debugPrint(
147
+ "Audio ($hashCode) srcBase64=$srcBase64, prevSrcBase64=$prevSrcBase64");
148
+
149
+ bool srcChanged = false;
150
+ if (src != "" && src != prevSrc) {
151
+ widget.control.state["src"] = src;
152
+ srcChanged = true;
153
+
154
+ // URL or file?
155
+ var assetSrc =
156
+ getAssetSrc(src, pageArgs.pageUri!, pageArgs.assetsDir);
157
+ if (assetSrc.isFile) {
158
+ await player?.setSourceDeviceFile(assetSrc.path);
159
+ } else {
160
+ await player?.setSourceUrl(assetSrc.path);
161
+ }
162
+ } else if (srcBase64 != "" && srcBase64 != prevSrcBase64) {
163
+ widget.control.state["srcBase64"] = srcBase64;
164
+ srcChanged = true;
165
+ await player?.setSourceBytes(base64Decode(srcBase64));
166
+ }
167
+
168
+ if (srcChanged) {
169
+ debugPrint("Audio.srcChanged!");
170
+ widget.backend.triggerControlEvent(widget.control.id, "loaded");
171
+ }
172
+
173
+ if (releaseMode != null && releaseMode != prevReleaseMode) {
174
+ debugPrint("Audio.setReleaseMode($releaseMode)");
175
+ widget.control.state["releaseMode"] = releaseMode;
176
+ await player?.setReleaseMode(releaseMode);
177
+ }
178
+
179
+ if (volume != null &&
180
+ volume != prevVolume &&
181
+ volume >= 0 &&
182
+ volume <= 1) {
183
+ widget.control.state["volume"] = volume;
184
+ debugPrint("Audio.setVolume($volume)");
185
+ await player?.setVolume(volume);
186
+ }
187
+
188
+ if (playbackRate != null &&
189
+ playbackRate != prevPlaybackRate &&
190
+ playbackRate >= 0 &&
191
+ playbackRate <= 2) {
192
+ widget.control.state["playbackRate"] = playbackRate;
193
+ debugPrint("Audio.setPlaybackRate($playbackRate)");
194
+ await player?.setPlaybackRate(playbackRate);
195
+ }
196
+
197
+ if (!kIsWeb &&
198
+ balance != null &&
199
+ balance != prevBalance &&
200
+ balance >= -1 &&
201
+ balance <= 1) {
202
+ widget.control.state["balance"] = balance;
203
+ debugPrint("Audio.setBalance($balance)");
204
+ await player?.setBalance(balance);
205
+ }
206
+
207
+ if (srcChanged && autoplay) {
208
+ debugPrint("Audio.resume($srcChanged, $autoplay)");
209
+ await player?.resume();
210
+ }
211
+
212
+ widget.backend.subscribeMethods(widget.control.id,
213
+ (methodName, args) async {
214
+ switch (methodName) {
215
+ case "play":
216
+ await player?.seek(const Duration(milliseconds: 0));
217
+ await player?.resume();
218
+ break;
219
+ case "resume":
220
+ await player?.resume();
221
+ break;
222
+ case "pause":
223
+ await player?.pause();
224
+ break;
225
+ case "release":
226
+ await player?.release();
227
+ break;
228
+ case "seek":
229
+ await player?.seek(Duration(
230
+ milliseconds: int.tryParse(args["position"] ?? "") ?? 0));
231
+ break;
232
+ case "get_duration":
233
+ return (await player?.getDuration())?.inMilliseconds.toString();
234
+ case "get_current_position":
235
+ return (await player?.getCurrentPosition())
236
+ ?.inMilliseconds
237
+ .toString();
238
+ }
239
+ return null;
240
+ });
241
+ }();
242
+
243
+ return const SizedBox.shrink();
244
+ });
245
+ }
246
+ }
@@ -0,0 +1,20 @@
1
+ import 'package:flet/flet.dart';
2
+
3
+ import 'audio.dart';
4
+
5
+ CreateControlFactory createControl = (CreateControlArgs args) {
6
+ switch (args.control.type) {
7
+ case "audio":
8
+ return AudioControl(
9
+ parent: args.parent,
10
+ control: args.control,
11
+ nextChild: args.nextChild,
12
+ backend: args.backend);
13
+ default:
14
+ return null;
15
+ }
16
+ };
17
+
18
+ void ensureInitialized() {
19
+ // nothing to initialize
20
+ }
@@ -0,0 +1,18 @@
1
+ name: flet_audio
2
+ description: Flet Audio control
3
+ homepage: https://flet.dev
4
+ repository: https://github.com/flet-dev/flet-audio/src/flutter/flet_audio
5
+ version: 0.1.0
6
+ environment:
7
+ sdk: '>=3.2.3 <4.0.0'
8
+ flutter: '>=1.17.0'
9
+ dependencies:
10
+ flutter:
11
+ sdk: flutter
12
+ collection: ^1.16.0
13
+ audioplayers: ^5.2.1
14
+ flet: ^0.25.2
15
+ dev_dependencies:
16
+ flutter_test:
17
+ sdk: flutter
18
+ flutter_lints: ^2.0.0
.DS_Store DELETED
Binary file
flet_audio/.DS_Store DELETED
Binary file
Binary file
@@ -1,14 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: flet-audio
3
- Version: 0.0.1
4
- Summary: Flet Audio control
5
- Author: Appveyor Systems Inc.
6
- Author-email: hello@flet.dev
7
- Requires-Python: >=3.8,<4.0
8
- Project-URL: homepage, https://flet.dev
9
- Download-URL:
10
- Description-Content-Type: text/markdown
11
-
12
- # Flet Audio
13
-
14
- Flet Audio control.
@@ -1,7 +0,0 @@
1
- .DS_Store,sha256=UGxWgJfmLLyazGK5A-uGE3FwdljfvRyUi6SV7VdJU-E,6148
2
- flet_audio/.DS_Store,sha256=1lFlJ5EFymdzGAUAaI30vcaaLHt3F1LwpG7xILf9jsM,6148
3
- flet_audio/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
4
- flet_audio-0.0.1.dist-info/.DS_Store,sha256=1lFlJ5EFymdzGAUAaI30vcaaLHt3F1LwpG7xILf9jsM,6148
5
- flet_audio-0.0.1.dist-info/METADATA,sha256=35ixfHvfoMBCEUPnW3UhI2EEXs1ktxmpMBiD0mdorHo,297
6
- flet_audio-0.0.1.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
7
- flet_audio-0.0.1.dist-info/RECORD,,