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

如何在React中一键按顺序播放音频?移动端Web App实现

Hey Johnny, let's break down how to build this cross-platform web app step by step. This solution works seamlessly on iOS and Android, and it’s designed to scale easily when you add more audio files later.

Core Approach

We’ll use vanilla HTML/CSS/JavaScript (no heavy frameworks needed) to keep it lightweight for mobile. The key pieces are:

  • A dropdown to select language and load the corresponding audio set
  • A start button to trigger the sequence playback
  • Async logic to handle audio playback, wait intervals, and scale to more files
Implementation Code

Here’s a complete, mobile-friendly implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Sequence Player</title>
    <style>
        /* Mobile-first styling */
        body {
            max-width: 400px;
            margin: 2rem auto;
            padding: 0 1rem;
            font-family: Arial, sans-serif;
        }
        .controls {
            margin-top: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        select, button {
            padding: 0.8rem;
            font-size: 1rem;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        #status {
            margin-top: 1rem;
            color: #333;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Audio Sequence Player</h1>
    <div class="controls">
        <select id="languageSelect">
            <option value="">Select Language</option>
            <option value="english">English</option>
            <option value="chinese">Chinese</option>
        </select>
        <button id="startBtn" disabled>Start Playback</button>
    </div>
    <div id="status"></div>

    <script>
        // Config object - easily add more languages/audio here later
        const audioConfig = {
            english: [
                { src: 'audio/english1.mp3', name: 'English Audio 1' },
                { src: 'audio/english2.mp3', name: 'English Audio 2' }
                // Add 8 more audio objects here when you need to scale to 10
            ],
            chinese: [
                { src: 'audio/chinese1.mp3', name: 'Chinese Audio 1' },
                { src: 'audio/chinese2.mp3', name: 'Chinese Audio 2' }
            ]
        };

        const languageSelect = document.getElementById('languageSelect');
        const startBtn = document.getElementById('startBtn');
        const statusDiv = document.getElementById('status');
        let currentAudioList = [];
        let isPlaying = false;

        // Handle language selection
        languageSelect.addEventListener('change', (e) => {
            const selectedLang = e.target.value;
            if (selectedLang) {
                currentAudioList = audioConfig[selectedLang];
                startBtn.disabled = false;
                statusDiv.textContent = `Ready to play ${selectedLang} audio sequence`;
            } else {
                currentAudioList = [];
                startBtn.disabled = true;
                statusDiv.textContent = '';
            }
        });

        // Handle playback sequence
        startBtn.addEventListener('click', async () => {
            if (isPlaying || currentAudioList.length === 0) return;
            
            isPlaying = true;
            startBtn.disabled = true;
            languageSelect.disabled = true;
            statusDiv.textContent = 'Starting playback...';

            const INTERVAL = 5000; // 5-second delay between audios (adjust as needed)

            for (let i = 0; i < currentAudioList.length; i++) {
                const audioItem = currentAudioList[i];
                statusDiv.textContent = `Playing: ${audioItem.name}`;
                
                // Create and play audio
                const audio = new Audio(audioItem.src);
                try {
                    await audio.play();
                    // Wait for the audio to finish playing
                    await new Promise(resolve => audio.addEventListener('ended', resolve, { once: true }));
                } catch (err) {
                    console.error('Error playing audio:', err);
                    statusDiv.textContent = `Error playing ${audioItem.name}`;
                    break;
                }

                // Wait for interval if not the last audio
                if (i < currentAudioList.length - 1) {
                    statusDiv.textContent = `Waiting ${INTERVAL/1000} seconds...`;
                    await new Promise(resolve => setTimeout(resolve, INTERVAL));
                }
            }

            // Reset after playback completes
            isPlaying = false;
            startBtn.disabled = false;
            languageSelect.disabled = false;
            statusDiv.textContent = 'Playback completed!';
        });
    </script>
</body>
</html>
Key Details to Know
  • Mobile Compliance: Both iOS and Android require audio playback to be triggered by a user gesture (like tapping a button). This code follows that rule by tying playback to the "Start" button click, so you won’t run into auto-play blocks.
  • Scalability: To add more audio files (up to 10 or more), just add new objects to the audioConfig arrays. The loop will automatically handle the sequence without any additional code changes.
  • Error Handling: If an audio file fails to load/play, the code will log the error and stop the sequence, so users aren’t left hanging.
  • User Feedback: The status div keeps users updated on what’s happening (playing, waiting, completed), which is important for mobile UX.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:10:13