chengmw
2026-03-26 85f3f863950fa1d807697da437591062868e782c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import React, { useState, useRef, useEffect } from 'react';
import { Button } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, ReloadOutlined, DownloadOutlined } from '@ant-design/icons';
import './AudioPlayer.css';
 
/**
 * 录音播放器组件
 * @param {string} recordUrl - 录音文件相对路径(可选)
 * @param {Blob|null} audioBlob - 音频Blob对象(可选)
 * @param {Function} onLoadAudio - 加载音频的函数,返回Promise<Blob>
 * @param {boolean} loading - 是否正在加载音频
 * @param {string} loadingText - 加载中的提示文字
 */
const AudioPlayer = ({ 
  recordUrl, 
  audioBlob, 
  onLoadAudio, 
  loading = false, 
  loadingText = '加载中...'
}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [loadError, setLoadError] = useState(false);
  const [audioSrc, setAudioSrc] = useState(null);
  const audioRef = useRef(null);
 
  // 格式化时间显示
  const formatTime = (seconds) => {
    if (!seconds || isNaN(seconds)) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };
 
  // 处理播放/暂停
  const handlePlayPause = () => {
    if (!audioRef.current) return;
    
    if (isPlaying) {
      audioRef.current.pause();
    } else {
      audioRef.current.play().catch(() => {
        setLoadError(true);
      });
    }
    setIsPlaying(!isPlaying);
  };
 
  // 处理时间更新
  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime);
    }
  };
 
  // 处理元数据加载
  const handleLoadedMetadata = () => {
    if (audioRef.current) {
      setDuration(audioRef.current.duration);
      setLoadError(false);
    }
  };
 
  // 处理加载错误
  const handleError = () => {
    setLoadError(true);
    setIsPlaying(false);
  };
 
  // 处理播放结束
  const handleEnded = () => {
    setIsPlaying(false);
    setCurrentTime(0);
  };
 
  // 重试加载
  const handleRetry = () => {
    setLoadError(false);
    if (onLoadAudio) {
      onLoadAudio();
    } else if (audioRef.current && audioSrc) {
      audioRef.current.load();
    }
  };
 
  // 处理进度条点击
  const handleProgressClick = (e) => {
    if (!audioRef.current || !duration) return;
    
    const progressBar = e.currentTarget;
    const rect = progressBar.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const newTime = (clickX / rect.width) * duration;
    
    audioRef.current.currentTime = newTime;
    setCurrentTime(newTime);
  };
 
  // 处理下载音频
  const handleDownload = () => {
    if (!audioBlob) return;
    
    // 从recordUrl中提取文件名
    let fileName = '录音文件.wav';
    if (recordUrl) {
      const parts = recordUrl.split(/[/\\]/);
      if (parts.length > 0) {
        fileName = parts[parts.length - 1];
        if (!fileName.endsWith('.wav')) {
          fileName += '.wav';
        }
      }
    }
    
    // 创建下载链接
    const blobUrl = URL.createObjectURL(audioBlob);
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(blobUrl);
  };
 
  // 计算进度百分比
  const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;
 
  // 当audioBlob变化时更新音频源
  useEffect(() => {
    if (audioBlob) {
      const url = URL.createObjectURL(audioBlob);
      setAudioSrc(url);
      setLoadError(false);
      return () => URL.revokeObjectURL(url);
    }
  }, [audioBlob]);
 
  // 加载中状态
  if (loading) {
    return (
      <div className="audio-player audio-player-loading">
        <div className="loading-content">
          <div className="loading-spinner"></div>
          <span className="loading-text">{loadingText}</span>
        </div>
      </div>
    );
  }
 
  // 无录音文件状态
  if (!recordUrl && !audioSrc) {
    return (
      <div className="audio-player audio-player-empty">
        <div className="empty-content">
          <span className="empty-icon">🎙️</span>
          <span className="empty-text">没有通话录音文件,无法播放</span>
        </div>
      </div>
    );
  }
 
  // 加载失败状态
  if (loadError) {
    return (
      <div className="audio-player audio-player-error">
        <span className="error-text">录音文件加载失败</span>
        <Button 
          type="link" 
          icon={<ReloadOutlined />} 
          onClick={handleRetry}
        >
          重试
        </Button>
      </div>
    );
  }
 
  return (
    <div className="audio-player">
      {audioSrc && (
        <audio
          ref={audioRef}
          src={audioSrc}
          onTimeUpdate={handleTimeUpdate}
          onLoadedMetadata={handleLoadedMetadata}
          onError={handleError}
          onEnded={handleEnded}
          preload="metadata"
        />
      )}
      
      <Button
        type="text"
        className="play-btn"
        icon={isPlaying ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
        onClick={handlePlayPause}
      />
      
      <div 
        className="progress-bar"
        onClick={handleProgressClick}
      >
        <div 
          className="progress-fill"
          style={{ width: `${progressPercent}%` }}
        />
      </div>
      
      <span className="time-display">
        {formatTime(currentTime)} / {formatTime(duration)}
      </span>
      
      <Button
        type="text"
        className="download-btn"
        icon={<DownloadOutlined />}
        onClick={handleDownload}
        disabled={!audioBlob}
        title="下载录音"
      />
    </div>
  );
};
 
export default AudioPlayer;