Files
pda-overseas-uniapp/src/utils/audio-feedback.js
T
2026-09-20 15:03:34 +08:00

55 lines
1.2 KiB
JavaScript

export const AUDIO_FEEDBACK_SOURCES = Object.freeze({
success: '/static/mp3/success.mp3',
error: '/static/mp3/fail.mp3'
})
let audioContext = null
let hasStartedPlayback = false
function getAudioContext() {
if (audioContext) return audioContext
if (typeof uni === 'undefined' || typeof uni.createInnerAudioContext !== 'function') return null
audioContext = uni.createInnerAudioContext()
audioContext.autoplay = false
audioContext.loop = false
audioContext.volume = 1
return audioContext
}
export function playFeedbackSound(type) {
const source = AUDIO_FEEDBACK_SOURCES[type]
const player = getAudioContext()
if (!source || !player) return false
try {
if (hasStartedPlayback) player.stop()
player.src = source
player.play()
hasStartedPlayback = true
return true
} catch (_) {
return false
}
}
export function playSuccessSound() {
return playFeedbackSound('success')
}
export function playErrorSound() {
return playFeedbackSound('error')
}
export function stopFeedbackSound() {
if (!audioContext) return
try { audioContext.stop() } catch (_) {}
}
export function destroyFeedbackSound() {
if (!audioContext) return
try { audioContext.destroy() } catch (_) {}
audioContext = null
hasStartedPlayback = false
}