Search code examples
javascriptreactjswavmu-law

How to convert ulaw format file to wav format reactjs


I am trying to play .ulaw format in reactjs, I didn't find any straight forward way to play the ulaw file. So I tried to convert ulaw format to wav, by using the wavfile plugin. But after conversion it playing different noise, I am not able to identify where is the actual error.

ulaw file details:

Sample Rate 8000

Bit rate 64

Channel MONO

import voice from '../src/app/components/voice.ulaw'
const WaveFile = require('wavefile').WaveFile;

let wav = new WaveFile();


const playUlawFile = () => {
    fetch(voice)
        .then(r => r.text())
        .then(text =>  Buffer.from(text, "utf-8").toString("base64"))
        .then(result =>{
            wav.bitDepth = '128000'
            wav.fromScratch(1, 8000, '64', result);
            wav.fromMuLaw();
            wav.toSampleRate(64000);
        return wav;

        }).then(wav => {
            audio = new Audio(wav.toDataURI())
            return audio;
        }).then(audio => {
            audio.play();

        })
}

Solution

  • Below changes worked for me, still some noise is there, but it can produce 80% matching sound.

    const readFile = () => {
        fetch(voice)
            .then(r => r.text())
            .then(text =>  btoa(unescape(encodeURIComponent(text)))         )
            .then(result =>{
                wav.fromScratch(1, 18000, '8m', Buffer.from(result, "base64"));
                wav.fromMuLaw(32);
               wav.toSampleRate(64000, {method: "sinc"});
               return wav;
            }).then(wav => {
                audio = new Audio(wav.toDataURI())
                return audio;
            }).then(audio => {
                audio.play();
            })
    }