| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import Taro from "@tarojs/taro";
- // 音频播放状态类型
- type AudioPlayStatus = 'idle' | 'playing' | 'paused' | 'stopped' | 'error';
- // 封装后的音频实例类型
- interface AudioInstance {
- play: () => void;
- pause: () => void;
- stop: () => void;
- destroy: () => void;
- onStatusChange: (callback: (status: AudioPlayStatus) => void) => void;
- getStatus: () => AudioPlayStatus;
- }
- export function playWavAudio(url: string): AudioInstance {
- const audio = Taro.createInnerAudioContext();
- let currentStatus: AudioPlayStatus = 'idle';
- let statusChangeCallback: ((status: AudioPlayStatus) => void) | null = null;
- // 更新状态并触发回调
- const updateStatus = (newStatus: AudioPlayStatus) => {
- currentStatus = newStatus;
- if (statusChangeCallback) {
- statusChangeCallback(newStatus);
- }
- };
- audio.src = url;
- // 事件监听
- audio.onPlay(() => updateStatus('playing'));
- audio.onPause(() => updateStatus('paused'));
- audio.onStop(() => updateStatus('stopped'));
- audio.onEnded(() => updateStatus('stopped'));
- audio.onError(() => {
- updateStatus('error');
- audio.destroy();
- });
- return {
- play: () => {
- if (currentStatus !== 'playing') {
- audio.play();
- }
- },
- pause: () => {
- if (currentStatus === 'playing') {
- audio.pause();
- }
- },
- stop: () => {
- if (currentStatus === 'playing' || currentStatus === 'paused') {
- audio.stop();
- }
- },
- destroy: () => {
- audio.destroy();
- updateStatus('idle');
- },
- onStatusChange: (callback) => {
- statusChangeCallback = callback;
- },
- getStatus: () => currentStatus,
- };
- }
|