Files
pda-uniapp/utils/audio-feedback.js
T
2026-07-30 18:04:37 +08:00

52 lines
1.1 KiB
JavaScript

export const AUDIO_FEEDBACK_SOURCES = Object.freeze({
success: '/static/mp3/success.mp3',
error: '/static/mp3/fail.mp3'
})
let audioContext = null
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 {
player.stop()
player.src = source
player.play()
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
}