Personalized action does not play audio on mobile devices

Hello!

I have created a custom action to automatically play the audio obtained in Eleven Labs. In the web version it works perfectly, but I can't get it to play on mobile devices, should I use another package?

¡Thanks!

// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/backend/schema/structs/index.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import 'package:just_audio/just_audio.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> playAudioAction(String text, String apiKey, String voiceId) async {
  final AudioPlayer player = AudioPlayer();

  try {
    String url = 'https://api.elevenlabs.io/v1/text-to-speech/$voiceId';
    final response = await http.post(
      Uri.parse(url),
      headers: {
        'accept': 'audio/mpeg',
        'xi-api-key': apiKey,
        'Content-Type': 'application/json',
      },
      body: json.encode({
        "text": text,
        "model_id": "eleven_monolingual_v1",
        "voice_settings": {"stability": .15, "similarity_boost": .75}
      }),
    );

    if (response.statusCode == 200) {
      await player.setAudioSource(
        ByteStreamAudioSource(response.bodyBytes),
      );
      player.play();
    } else {
      throw Exception('Error fetching the audio');
    }
  } catch (error) {
    print('Error in playAudioAction: $error');
  }
}

class ByteStreamAudioSource extends StreamAudioSource {
  final List<int> bytes;

  ByteStreamAudioSource(this.bytes);

  @override
  Future<StreamAudioResponse> request([int? start, int? end]) async {
    start ??= 0;
    end ??= bytes.length;
    return StreamAudioResponse(
      sourceLength: bytes.length,
      contentLength: end - start,
      offset: start,
      stream: Stream.value(Uint8List.fromList(bytes.sublist(start, end))),
      contentType: 'audio/mpeg',
    );
  }
}

// Set your action name, define your arguments and return parameter,
// and then add the boilerplate code using the button on the right!
2
8 replies