55// - the code between BEGIN USER CODE and END USER CODE
66// - the code between BEGIN EXTRA CODE and END EXTRA CODE
77// Other code you write will be lost the next time you deploy the project.
8- import Sound from "react-native-sound " ;
8+ import TrackPlayer , { State , Event } from "react-native-track-player " ;
99
1010// BEGIN EXTRA CODE
1111// END EXTRA CODE
@@ -19,7 +19,7 @@ import Sound from "react-native-sound";
1919 */
2020export async function PlaySound ( audioFile ?: mendix . lib . MxObject ) : Promise < void > {
2121 // BEGIN USER CODE
22- // Documentation https://github.com/zmxv/react-native-sound
22+ // Documentation https://rntp.dev
2323
2424 if ( ! audioFile ) {
2525 return Promise . reject ( new Error ( "Input parameter 'Audio file' is required" ) ) ;
@@ -34,19 +34,39 @@ export async function PlaySound(audioFile?: mendix.lib.MxObject): Promise<void>
3434 const changedDate = audioFile . get ( "changedDate" ) as number ;
3535 const url = mx . data . getDocumentUrl ( guid , changedDate ) ;
3636
37- const audio = new Sound ( url , undefined , error => {
38- if ( error ) {
39- return Promise . reject ( new Error ( error ) ) ;
37+ try {
38+ // Initialize the player if it hasn't been set up yet
39+ const state = await TrackPlayer . getPlaybackState ( ) ;
40+ if ( state . state === State . None ) {
41+ await TrackPlayer . setupPlayer ( {
42+ maxCacheSize : 1024
43+ } ) ;
4044 }
4145
42- audio . play ( success => {
43- audio . release ( ) ;
44- if ( success ) {
45- return Promise . resolve ( ) ;
46- }
47- return Promise . reject ( new Error ( "Playback failed due to an audio encoding error" ) ) ;
46+ await TrackPlayer . reset ( ) ;
47+ await TrackPlayer . add ( {
48+ id : guid ,
49+ url ,
50+ title : `Audio ${ guid } ` ,
51+ artist : "Mendix App"
4852 } ) ;
49- } ) ;
53+
54+ await TrackPlayer . play ( ) ;
55+
56+ return new Promise < void > ( ( resolve , reject ) => {
57+ const subscription = TrackPlayer . addEventListener ( Event . PlaybackState , event => {
58+ if ( event . state === State . Stopped || event . state === State . Ended ) {
59+ subscription . remove ( ) ;
60+ resolve ( ) ;
61+ } else if ( event . state === State . Error ) {
62+ subscription . remove ( ) ;
63+ reject ( new Error ( event . error . message || "Playback error" ) ) ;
64+ }
65+ } ) ;
66+ } ) ;
67+ } catch ( error ) {
68+ return Promise . reject ( new Error ( `Failed to play audio: ${ error } ` ) ) ;
69+ }
5070
5171 // END USER CODE
5272}
0 commit comments