convert audio wav to mp3 (#552)
parent
b91e226063
commit
397a92f2ee
@ -1,23 +1,13 @@
|
|||||||
from services.errors.base import BaseServiceError
|
class NoAudioUploadedServiceError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
class NoAudioUploadedServiceError(BaseServiceError):
|
|
||||||
error_code = 'no_audio_uploaded'
|
|
||||||
description = "Please upload your audio."
|
|
||||||
code = 400
|
|
||||||
|
|
||||||
|
class AudioTooLargeServiceError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
class AudioTooLargeServiceError(BaseServiceError):
|
|
||||||
error_code = 'audio_too_large'
|
|
||||||
description = "Audio size exceeded. {message}"
|
|
||||||
code = 413
|
|
||||||
|
|
||||||
|
class UnsupportedAudioTypeServiceError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
class UnsupportedAudioTypeServiceError(BaseServiceError):
|
class ProviderNotSupportSpeechToTextServiceError(Exception):
|
||||||
error_code = 'unsupported_audio_type'
|
pass
|
||||||
description = "Audio type not allowed."
|
|
||||||
code = 415
|
|
||||||
|
|
||||||
class ProviderNotSupportSpeechToTextServiceError(BaseServiceError):
|
|
||||||
error_code = 'provider_not_support_speech_to_text'
|
|
||||||
description = "Provider not support speech to text. {message}"
|
|
||||||
code = 400
|
|
||||||
@ -0,0 +1,38 @@
|
|||||||
|
import lamejs from 'lamejs'
|
||||||
|
|
||||||
|
export const convertToMp3 = (recorder: any) => {
|
||||||
|
const wav = lamejs.WavHeader.readHeader(recorder.getWAV())
|
||||||
|
const { channels, sampleRate } = wav
|
||||||
|
const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128)
|
||||||
|
const result = recorder.getChannelData()
|
||||||
|
const buffer = []
|
||||||
|
|
||||||
|
const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2)
|
||||||
|
const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2)
|
||||||
|
const remaining = leftData.length + (rightData ? rightData.length : 0)
|
||||||
|
|
||||||
|
const maxSamples = 1152
|
||||||
|
for (let i = 0; i < remaining; i += maxSamples) {
|
||||||
|
const left = leftData.subarray(i, i + maxSamples)
|
||||||
|
let right = null
|
||||||
|
let mp3buf = null
|
||||||
|
|
||||||
|
if (channels === 2) {
|
||||||
|
right = rightData.subarray(i, i + maxSamples)
|
||||||
|
mp3buf = mp3enc.encodeBuffer(left, right)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
mp3buf = mp3enc.encodeBuffer(left)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mp3buf.length > 0)
|
||||||
|
buffer.push(mp3buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
const enc = mp3enc.flush()
|
||||||
|
|
||||||
|
if (enc.length > 0)
|
||||||
|
buffer.push(enc)
|
||||||
|
|
||||||
|
return new Blob(buffer, { type: 'audio/mp3' })
|
||||||
|
}
|
||||||
@ -0,0 +1 @@
|
|||||||
|
declare module 'lamejs';
|
||||||
Loading…
Reference in New Issue