How to Play Audio Through Earpiece on Both iOS and Android in Flutter

I am working on a Flutter project where I need to play audio through the earpiece (not the speaker) on both iOS and Android devices. Below is a sample of my current implementation:

import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:legalis/provider/communication/communication_provider.dart';
import 'package:legalis/provider/navigation/navigation_provider.dart';
import 'package:legalis/widgets/call/CallCountDown.dart';
import 'package:legalis/widgets/call_close_review_bottom_sheet.dart';

class CallPage extends StatefulWidget {
  CallPage({super.key, required this.callToken});

  final String? callToken;

  @override
  State<CallPage> createState() => _CallPageState();
}

class _CallPageState extends State<CallPage> with TickerProviderStateMixin {
  late AnimationController _controller;
  final int levelClock = 28;
  late AudioPlayer _player;

  @override
  void initState() {
    super.initState();
    // Start the countdown timer when the widget is first displayed
    final communicationProvider =
        Provider.of<CommunicationProvider>(context, listen: false);
    communicationProvider.startTimer(Duration(seconds: 70));

    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: levelClock),
    );

    _controller.forward();

    _player = AudioPlayer();

    _player.setAudioContext(
      AudioContext(
          android: AudioContextAndroid(isSpeakerphoneOn: false), // Set to false for earpiece
          iOS: AudioContextIOS(category: AVAudioSessionCategory.playAndRecord)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final navigationProvider = Provider.of<NavigationProvider>(context);

    return Scaffold(
      backgroundColor: const Color(0xFF000E2B),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              margin: const EdgeInsets.only(top: 30),
              width: MediaQuery.of(context).size.width,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 72,
                    height: 72,
                    decoration: ShapeDecoration(
                      image: DecorationImage(
                        image: NetworkImage(
                          'https://media.licdn.com/dms/image/D4E03AQHWd3HiWA1I7g/profile-displayphoto-shrink_800_800/0/1693132754168?e=1723680000&v=beta&t=oyhL1JDIwlEP2yKtVEAvlQ-Z1k-EYM0A0whwep-TWXc',
                        ),
                        fit: BoxFit.fill,
                      ),
                      shape: const OvalBorder(),
                    ),
                  ),
                  const SizedBox(height: 13),
                  const Text(
                    'Məhəmməd Məhəmmədov',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 32,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 13),
                  Countdown(
                    warning: (p0) {
                      if (p0) _player.play(AssetSource('voice/call_warning.mp3'));
                    },
                    onEnd: (bool isEnd) {
                      if (isEnd) {
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          if (mounted) {
                            Navigator.pop(context);
                            navigationProvider.setNavVisible(false);
                            showModalBottomSheet(
                              context: context,
                              backgroundColor: const Color(0xFF173786),
                              builder: (context) =>
                                  const CallCloseReviewBottomSheet(),
                            ).then(
                              (value) => navigationProvider.setNavVisible(true),
                            );
                          }
                        });
                      }
                    },
                    key: UniqueKey(),
                    animation: StepTween(
                      begin: levelClock, // THIS IS A USER ENTERED NUMBER
                      end: 0,
                    ).animate(_controller),
                  ),
                ],
              ),
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              height: 93,
              decoration: const ShapeDecoration(
                color: Color(0xFF333E55),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10),
                    topRight: Radius.circular(10),
                  ),
                ),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  GestureDetector(
                    child: SvgPicture.asset('assets/icons/volume-high.svg'),
                  ),
                  GestureDetector(
                    child: SvgPicture.asset('assets/icons/microphone-slash.svg'),
                  ),
                  Consumer<CommunicationProvider>(
                    builder: (context, provider, child) {
                      if (!provider.isConnected) {
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          if (mounted) {
                            Navigator.pop(context);
                            navigationProvider.setNavVisible(false);
                            showModalBottomSheet(
                              context: context,
                              backgroundColor: const Color(0xFF173786),
                              builder: (context) =>
                                  const CallCloseReviewBottomSheet(),
                            ).then(
                              (value) => navigationProvider.setNavVisible(true),
                            );
                          }
                        });
                      }
                      return GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          navigationProvider.setNavVisible(false);
                          showModalBottomSheet(
                            context: context,
                            backgroundColor: const Color(0xFF173786),
                            builder: (context) =>
                                const CallCloseReviewBottomSheet(),
                          ).then(
                            (value) => navigationProvider.setNavVisible(true),
                          );
                        },
                        child: SvgPicture.asset('assets/icons/Frame 230.svg'),
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    _player.dispose();
    super.dispose();
  }
}

have set the isSpeakerphoneOn property to false for Android and the category to AVAudioSessionCategory.playAndRecord for iOS, but the audio still plays through the speaker. How can I ensure the audio plays through the earpiece on both platforms?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật