skip to Main Content

I want to make an quotes app with background audio in PageView with images when scrolling up
then next audio play, if the user standing on specific quote the crossponding audio repeating continuously untill the user scroll up if scroll
then play nextAudio for static usage quotes single strings are appering

but did not work pretty

import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:just_audio_background/just_audio_background.dart';
import 'package:just_audio/just_audio.dart';

// import 'package:rxdart/rxdart.dart';

class AudioPlayerScreen extends StatefulWidget {
  const AudioPlayerScreen({super.key});

  @override
  State<AudioPlayerScreen> createState() => _AudioPlayerScreenState();
}

class _AudioPlayerScreenState extends State<AudioPlayerScreen> {
  late AudioPlayer audioPlayer;
  List<String> dataStored = ['ali ahmad', 'noman', 'shabaz', 'Ali Akbar'];
  int currentIndex = 0; // Track the current index for audio playback
  bool isRepeating = true; // Flag to control audio looping
  List<String> audioPaths = ['motivational', 'inspirational'];
  @override
  void initState() {
    super.initState();
    audioPlayer = AudioPlayer()
      ..onPlayerStateChanged.listen((playerState) {
        if (playerState == PlayerStateSteam.COMPLETED) {
          if (isRepeating) {
            _playAudio(currentIndex); // Repeat audio if looping enabled
          }
        }
      });
    _playAudio(currentIndex); // Start playing the initial audio
  }

  @override
  void dispose() {
    audioPlayer.dispose();
    super.dispose();
  }

 void _playAudio(int index) async {
  final String audioPath = 'assets/audio/${audioPaths[index]}.mp3';
  await audioPlayer.setAudioSource(AssetAudioSource.asset(audioPath));
  await audioPlayer.play();
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('example'),
        centerTitle: true,
      ),
      body: PageView.builder(
        scrollDirection: Axis.vertical,
        itemCount: dataStored.length,
        itemBuilder: (context, index) {
          return Stack(
            children: [
              const Image(
                width: 500.0,
                image: AssetImage('assets/roadImg.jpg'),
                fit: BoxFit.fill,
              ),
              Container(
                decoration:
                    BoxDecoration(border: Border.all(color: Colors.black)),
                child: Center(
                  child: Text(
                    dataStored[index],
                    style: const TextStyle(fontSize: 30.0, color: Colors.white),
                  ),
                ),
              ),
              // Controls(audioPlayer: audioPlayer),
              Positioned(
                top: MediaQuery.of(context).size.height * 0.63,
                right: 0,
                bottom: 0,
                child: IconButton(
                  onPressed: () {
                    print('clicked');
                  },
                  icon: const Icon(Icons.comment, color: Colors.white),
                ),
              ),
            ],
          );
        },
        onPageChanged: (newIndex) {
          if (currentIndex != newIndex) {
            isRepeating = false; // Stop repeating when page changes
            _playAudio(newIndex);
            currentIndex = newIndex;
          }
        },
      ),
    );
  }
}

2

Answers


  1. Chosen as BEST ANSWER
    here my whole component:
    
    // import 'dart:io';
    
    // import 'package:audioplayers/audioplayers.dart';
    
    import 'package:flutter/material.dart';
    import 'package:flutter/widgets.dart';
    import 'package:just_audio/just_audio.dart';
    
    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      final AudioPlayer player = AudioPlayer();
      List<String> dataStored = ['ali ahmad', 'noman', 'shabaz', 'Ali Akbar'];
      int currentIndex = 0;
    
      final playlist = ConcatenatingAudioSource(
        useLazyPreparation: true,
        shuffleOrder: DefaultShuffleOrder(),
        children: [
          AudioSource.uri(Uri.parse('assets://assets/audio/motivational.mp3')),
          AudioSource.uri(Uri.parse('assets://assets/audio/inspirational.mp3')),
        ],
      );
      @override
      void initState() {
        initAudio();
        super.initState();
      }
    
      @override
      void dispose() {
        player.dispose();
        super.dispose();
      }
    
      Future<void> initAudio() async {
        await player.setAudioSource(
          playlist,
          initialIndex: 0,
          initialPosition: Duration.zero,
        );
        await player
            .setLoopMode(LoopMode.one); // Set playlist to loop (off|all|one)
    
        await player.seek(Duration.zero, index: currentIndex);
        if (!player.playing) {
          await player.play();
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('example'),
            centerTitle: true,
          ),
          body: PageView.builder(
            scrollDirection: Axis.vertical,
            itemCount: dataStored.length,
            itemBuilder: (context, index) {
              return Stack(
                children: [
                  const Image(
                    width: 500.0,
                    image: AssetImage('assets/roadImg.jpg'),
                    fit: BoxFit.fill,
                  ),
                  Container(
                    decoration:
                        BoxDecoration(border: Border.all(color: Colors.black)),
                    child: Center(
                      child: Text(
                        dataStored[index],
                        style: const TextStyle(fontSize: 30.0, color: Colors.white),
                      ),
                    ),
                  ),
                  // Controls(audioPlayer: audioPlayer),
                  Positioned(
                    top: MediaQuery.of(context).size.height * 0.63,
                    right: 0,
                    bottom: 0,
                    child: IconButton(
                      onPressed: () {
                        print('clicked');
                      },
                      icon: const Icon(Icons.comment, color: Colors.white),
                    ),
                  ),
                ],
              );
            },
            onPageChanged: (newIndex) {
              if (currentIndex != newIndex) {
                currentIndex = newIndex;
              }
            },
          ),
        );
      }
    }
    

  2. Rather then this make a playlist with audio source and pass it directly to AudioPlayer. And on page change use seekTo(position,pageViewIndex)

    final AudioPlayer player = AudioPlayer();
    
    // Define the playlist
      final playlist = ConcatenatingAudioSource(
        // Start loading next item just before reaching it
        useLazyPreparation: true,
        // Customise the shuffle algorithm
        shuffleOrder: DefaultShuffleOrder(),
        // Specify the playlist items
        children: [audiosources],
      );
    
    Future<void> initAudio() async {
        await player.setAudioSource(
          playlist,
          initialIndex: 0,
          initialPosition: Duration.zero,
        );
        await player
            .setLoopMode(LoopMode.one); // Set playlist to loop (off|all|one)
      }
    

    and then use this to play other video

    await player.seek(position, index: pageIndex);
    if (!player.playing) {
           await player.play();
         }
    

    or you can also use player.seekToNext() depending upon your use case.
    Also save this position for each audio ,such that when you go to previous page, you can start from the point where you left

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search