You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter名言App:PageView图片背景音频播放逻辑异常求助

问题修复:名言App垂直PageView音频循环与切换功能优化

原代码核心问题

  • 音频列表audioPaths长度(2个)与名言列表dataStored长度(4个)不匹配,切换到索引2、3时会触发资源找不到错误
  • 播放器状态枚举拼写错误:PlayerStateSteam.COMPLETED应为PlayerState.COMPLETED
  • 页面切换时仅关闭循环但未重新开启,导致新页面音频无法循环
  • 切换音频时未先停止当前播放,可能出现音频重叠或加载异常
  • 手动监听播放完成事件实现循环的方式冗余,可直接使用just_audio自带的循环模式

修正后的完整代码

import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.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'];
  List<String> audioPaths = [
    'motivational', 
    'inspirational', 
    'courage', 
    'wisdom' // 新增两个音频路径,与名言数量匹配
  ];
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    audioPlayer = AudioPlayer();
    // 初始化播放第一个音频并设置循环
    _playAudio(currentIndex, isLoop: true);
  }

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

  Future<void> _playAudio(int index, {required bool isLoop}) async {
    // 先停止当前播放,避免音频重叠
    await audioPlayer.stop();
    final String audioPath = 'assets/audio/${audioPaths[index]}.mp3';
    await audioPlayer.setAudioSource(
      AssetAudioSource(audioPath),
      initialPosition: Duration.zero,
    );
    // 设置循环模式:单曲循环或不循环
    audioPlayer.setLoopMode(isLoop ? LoopMode.one : LoopMode.off);
    await audioPlayer.play();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('名言音频'),
        centerTitle: true,
      ),
      body: PageView.builder(
        scrollDirection: Axis.vertical,
        itemCount: dataStored.length,
        itemBuilder: (context, index) {
          return Stack(
            fit: StackFit.expand,
            children: [
              Image.asset(
                'assets/roadImg.jpg',
                fit: BoxFit.cover,
              ),
              Container(
                decoration: BoxDecoration(border: Border.all(color: Colors.black)),
                child: Center(
                  child: Text(
                    dataStored[index],
                    style: const TextStyle(fontSize: 30.0, color: Colors.white),
                  ),
                ),
              ),
              Positioned(
                top: MediaQuery.of(context).size.height * 0.63,
                right: 16,
                child: IconButton(
                  onPressed: () {
                    print('评论按钮点击');
                  },
                  icon: const Icon(Icons.comment, color: Colors.white),
                ),
              ),
            ],
          );
        },
        onPageChanged: (newIndex) {
          if (currentIndex != newIndex) {
            // 切换到新页面时,播放对应音频并开启单曲循环
            _playAudio(newIndex, isLoop: true);
            currentIndex = newIndex;
          }
        },
      ),
    );
  }
}

关键修改说明

  1. 列表匹配:补充audioPaths的数量与dataStored一致,避免索引越界错误
  2. 循环逻辑优化:使用just_audio内置的LoopMode.one实现单曲循环,替代手动监听播放完成事件的冗余代码
  3. 页面切换处理:切换页面时先停止当前音频,再加载并播放新音频,同时重新开启循环模式
  4. UI细节优化:调整Stack的fit属性为StackFit.expand,让背景图片充满整个页面;调整图标按钮的位置,避免超出屏幕

内容的提问来源于stack exchange,提问作者usama haider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:53:10