Giter Club home page Giter Club logo

crunker's Introduction

Crunker

Simple way to merge, concatenate, play, export and download audio files with the Web Audio API.

  • No dependencies
  • Tiny 2kB gzipped
  • Written in Typescript

View online demos

Installation

yarn add crunker
npm install crunker

Example

let crunker = new Crunker();

crunker
  .fetchAudio('/song.mp3', '/another-song.mp3')
  .then((buffers) => {
    // => [AudioBuffer, AudioBuffer]
    return crunker.mergeAudio(buffers);
  })
  .then((merged) => {
    // => AudioBuffer
    return crunker.export(merged, 'audio/mp3');
  })
  .then((output) => {
    // => {blob, element, url}
    crunker.download(output.blob);
    document.body.append(output.element);
    console.log(output.url);
  })
  .catch((error) => {
    // => Error Message
  });

crunker.notSupported(() => {
  // Handle no browser support
});

Condensed Example

let crunker = new Crunker();

crunker
  .fetchAudio('/voice.mp3', '/background.mp3')
  .then((buffers) => crunker.mergeAudio(buffers))
  .then((merged) => crunker.export(merged, 'audio/mp3'))
  .then((output) => crunker.download(output.blob))
  .catch((error) => {
    throw new Error(error);
  });

Input file Example

let crunker = new Crunker();

const onFileInputChange = async (target) => {
  const buffers = await crunker.fetchAudio(...target.files, '/voice.mp3', '/background.mp3');
};

<input onChange={onFileInputChange(this)} type="file" accept="audio/*" />;

Other Examples

Merge

merge

Concat

concat

Methods

For more detailed API documentation, view the Typescript typings.

new Crunker()

Create a new instance of Crunker. You may optionally provide an object with a sampleRate key, but it will default to the same sample rate as the internal audio context, which is appropriate for your device.

crunker.fetchAudio(songURL, anotherSongURL)

Fetch one or more audio files.
Returns: an array of audio buffers in the order they were fetched.

crunker.mergeAudio(arrayOfBuffers);

Merge two or more audio buffers.
Returns: a single AudioBuffer object.

crunker.concatAudio(arrayOfBuffers);

Concatenate two or more audio buffers in the order specified.
Returns: a single AudioBuffer object.

crunker.padAudio(buffer, padStart, seconds);

Pad the audio with silence, at the beginning, the end, or any specified points through the audio.
Returns: a single AudioBuffer object.

crunker.sliceAudio(buffer, start, end, fadeIn, fadeOut);

Slice the audio to the specified range, removing any content outside the range. Optionally add a fade-in at the start and a fade-out at the end to avoid audible clicks.

  • buffer: The audio buffer to be trimmed.
  • start: The starting second from where the audio should begin.
  • end: The ending second where the audio should be trimmed.
  • fadeIn: (Optional) Number of seconds for the fade-in effect at the beginning. Default is 0.
  • fadeOut: (Optional) Number of seconds for the fade-out effect at the end. Default is 0.

Returns: a single AudioBuffer object.

crunker.export(buffer, type);

Export an audio buffers with MIME type option.
Type: e.g. 'audio/mp3', 'audio/wav', 'audio/ogg'. IMPORTANT: the MIME type does not change the actual file format. It will always be a WAVE file under the hood.
Returns: an object containing the blob object, url, and an audio element object.

crunker.download(blob, filename);

Automatically download an exported audio blob with optional filename.
Filename: String not containing the .mp3, .wav, or .ogg file extension.
Returns: the HTMLAnchorElement element used to simulate the automatic download.

crunker.play(buffer);

Starts playing the exported audio buffer in the background.
Returns: the HTMLAudioElement.

crunker.notSupported(callback);

Execute custom code if Web Audio API is not supported by the users browser.
Returns: The callback function.

Properties

For more detailed API documentation, view the Typescript typings.

crunker.context

Access the AudioContext used internally by a given Crunker.
Returns: AudioContext.

License

MIT

crunker's People

Contributors

27medkamal avatar alynva avatar davwheat avatar dependabot[bot] avatar fzxt avatar homm avatar itgm avatar jaggad avatar lmiller1990 avatar mikeyzat avatar thecoolpeople avatar thekip avatar tothehit avatar yudori avatar zackradisic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

crunker's Issues

Misleading README and method naming regarding format of exported file

This is a nice little library and I was happy to use it and learn from it.
Sadly it turns out that it ONLY exports in WAV format, regardless of what the chosen MIME type is.
As even the README examples show exporting with "audio/mp3" I believed that the library does it and only after implementing everything realized that the files are much larger and WAV indeed.

Digging in the code revealed a comment about this, but I think it should be explicitly stated somewhere in the README.
Personally, I would suggest the method to be renamed to "wav_export" in a potential future release

Thanks for the consideration

Sample rate change

We use Crunker to merge full length tracks with audio tags. Users who upload their tracks to be tagged on Windows machine report that that the audio has been pitched down (i.e the original track has been stretched to meet a large sample rate). However, this issue cannot be replicated when using crunker to merge the same audio on Windows machines.

not working on safari (ios / mac)?

Hello !
i am using this repository to merge 2 audio files.
It works on all browsers except safari (I tried it on iphone and ipad). Is it just my problem?
Do you have any suggestions?

Limit of the maximum audio track duration?

Hey!

I am trying to concatenate 2 (or more) audio files that are multiple minutes in size. TO do it, I need to load each of them to crunker. However, there is a problem: the duration of each track is limited to 17.544.

I have experimented locally, and have narrowed down the issue to decodeAudioData function, used inside of the fetchAudio function. More specifically:

const TEST_AUDIO = 'https://listen.technology/old-article-cache/ZGVsZmkvNTQzNDcyNDQ=';

(async () => {
  const buffer = await fetch(TEST_AUDIO).then(res => res.arrayBuffer());
  const blob = new Blob([buffer], { type: 'audio/mp3' });
  const url = URL.createObjectURL(blob); 
  const audio = new Audio();
  audio.src = url;
  await audio.play();
  await audio.pause();
  console.log(audio.duration); // results in 75.63525
  const audioContext = new AudioContext();
  const audioBuffer = await audioContext.decodeAudioData(buffer);
  console.log(audioBuffer.duration); // results in 17.544
})()

I did not find any information about any limits with decodeAudioData, therefore, I suspect my MP3 file might be somewhat invalid.

Cannot read property 'getChannelData' of undefined

Hello. Is it possible to merge two blob files?

I am trying every possible way to merge the audio of two blobs.
Your package seems the perfect solution.

But when I am trying it, I am getting the following error:

Cannot read property 'getChannelData' of undefined

This is the code. Just as in the doc. I am passing the two blobs as parameters:

let audio = new Crunker()
audio
  .fetchAudio(this.blobArray[0], this.blobArray[1])
  .then(buffers => {
    console.log({buffers})
    audio.mergeAudio(buffers);
  })
  .then(merged => {
    // => AudioBuffer
    console.log({merged})
    audio.export(merged, "audio/mp3");
  })
  .then(output => {
    // => {blob, element, url}
    console.log({output})
    audio.download(output.blob)
    document.append(output.element)
    console.log(output.url)
  })
  .catch(error => {
    console.log({error})
  });

This is a print of the console.log of each step:
It seems that nothing is returned from the second promise.

screen shot 2018-09-28 at 16 35 36

Do you know why I am getting that error?

Handling Unpredictable MediaError AUDIO_RENDERER_ERROR with HTML Audio Element

crunker
     .fetchAudio('./audio_1.mp3', './audio_2.mp3')
     .then(buffers => {
        // => [AudioBuffer, AudioBuffer]
        return crunker.mergeAudio(buffers)
     })
     .then(merged => {
        // => AudioBuffer
        return crunker.export(merged, 'audio/mp3')
     })
     .then(output => {
        crunker.download(output.blob)
        document.body.append(output.element)
        console.log('output url', output.url)
     })
     .catch(error => {
        // => Error Message
     })

When attempting to play the audio url from crunker using the HTML audio element, it sometimes fails to play, resulting in a MediaError with the message 'AUDIO_RENDERER_ERROR' and error code 3. When trying to play multiple times, the audio starts to play randomly.

We have also reported the same issue in Chromium -> https://issues.chromium.org/issues/333024284.

Please let us know if there are any insights regarding the issue.

Concatenation

  mediaRecorder.onstop = (ev)=>{
                let blob = new Blob(chunks, { 'type' : 'video/mp3;' });
                chunks = [];
                let videoURL = window.URL.createObjectURL(blob);
                vidSave.src = videoURL;
            }
        })
        .catch(function(err) { 
            console.log(err.name, err.message); 
        });

        document.querySelector('#press').addEventListener('click',function() {
            var audio =  new Crunker.default({ sampleRate: 44100 });
            let file = document.querySelector('#vid2');

            audio
            .fetchAudio("file","example1.mp3")
            .then(buffers => audio.concatAudio(buffers))
            .then(merged => audio.export(merged, "audio/wav"))
    .then(output => audio.download(output.blob))
    .catch(error => {
      throw new Error(error);
    });
        });

Is an implementation like this valid using your library? I am trying to get an audio recording from the user through the browser. I then convert it into a blob and try to concatenate that blob with a local audio file. Is this possible with the library?

enhancement Beatmachine

Hello out there.

I have written a small Beatmachine, but in pure js. Perhaps one of you want to implement that in typescript and add it to crunker.

I have no experience in typescript, so I am not able to help.

Code

mergeOneLine = async function(crunker, buffer, times){
    let audios = times.map(t => crunker.padAudio(buffer, 0, t))
    return crunker.mergeAudio(audios)
}

beatBuilder = async function(crunker, beatConf, buffers, beatTiming){
    let beatLines = await Promise.all(buffers.map((_,i) => {
        return mergeOneLine(crunker, buffers[i], beatTiming[i].map(bt => bt*beatConf.timing))
    }))
    let beat = await crunker.mergeAudio(beatLines)
    return await mergeOneLine(crunker, beat, Array.from(Array(beatConf.repeats).keys()).map(e => beatConf.delayStart+e*beatConf.beats*beatConf.timing))
}

window.onload = async function(){
    let crunker = new Crunker.default({sampleRate:96000});
    let [hihats] = await crunker.fetchAudio('./drumms_Hi-Hats_Open_Hat.mp3');
    let [dirtBase] = await crunker.fetchAudio('./drumms_dirt_base.mp3');
    
    //add pause to audio
    beat = await beatBuilder(crunker, {delayStart: 1, timing:0.5, repeats: 4, beats: 4},
        [dirtBase, hihats], [
        [0, 1.5, 2],
        [1, 3]
    ])
    
    
    let merged = await crunker.mergeAudio([beat])
    crunker.play(merged);
    let output = await crunker.export(merged, 'audio/ogg');
    await crunker.download(output.blob, 'merged');
}

Description:

mergeOneLine will generate a repeated sound at the timestamps times
beatBuilder will generate a buffer from multiple sounds and timestamps of that sound and will repeat that x times

Have a nice day!

Add travis build

Would be nice to build and test this library on travis-ci.org

Concatenated Files Too Large

Not sure what is causing this, hoping someone can help me out.

When I concatenate 3 mp3 files that are each about 8.5Mb in size, fetched from AWS S3 bucket, the resultant mp3 file after concatenation and download is a whopping 280Mb, which is about 10x what I would expect.

If I get that large file and then using a program like VLC player I stream to export as a fresh mp3 file, it is reduced to about 30Mb, closer to what I would expect.

FWIW, The Content-Type metadata of the files on the S3 bucket is set to audio/mpeg.

Is there some obvious configuration/setting that can resolve this ?

Merging results in large waveform file.

Wonderful tool - so helpful.

I am merging two audio tracks - a background track that is uploaded and a voice track that is recorded in the browser.

The merged track is ending up quite a bit larger than the original tracks.

I found your recommendation to reduce the sample rate [ https://github.com//issues/24 ]. This did reduce the file size by half, but it's still very large and came at the expense of fidelity.

A specific example:
Background mp3 | 1hr | 76mb
Recording | 25sec | 400kb
Crunker result | 1 hr | 275mb (550mb before adjusting the Crunker constructor sample rate to 22050)

Is it possible to get the file size down in Crunker?

crunker-master/examples/server/index.html not working?

Hello !
I am using this repository to merge 2 audio files.
I found some error in console of chrome "crunker-master/examples/server/index.html".
Please give me somey suggestions?

crunker.js:1 Fetch API cannot load file:///E:/crunker-master/examples/server/1.mp3. URL scheme "file" is not supported.
(anonymous) @ crunker.js:1
value @ crunker.js:1
doTheWork @ index.html:27
handleMerge @ index.html:18
onclick @ index.html:10
19:22:36.849 crunker.js:1 Fetch API cannot load file:///E:/crunker-master/examples/server/2.mp3. URL scheme "file" is not supported.
(anonymous) @ crunker.js:1
value @ crunker.js:1
doTheWork @ index.html:27
handleMerge @ index.html:18
onclick @ index.html:10
19:22:36.850 crunker.js:1 Uncaught (in promise) TypeError: Failed to fetch
at crunker.js:1
at Array.map ()
at e.value (crunker.js:1)
at doTheWork (index.html:27)
at handleMerge (index.html:18)
at HTMLButtonElement.onclick (index.html:10)

Concatenate MP4 file - speed is slower than the original mp4

Hello,

I'm using your lib for a project of media player.
I have to upload several mp4 files, concatenate them and read the audio file created by crunker.
The problem is that the final audio file is slower than the original ones. The speed of the concatenate file is a bit slower.
Is it normal?

This is how I use it:

private async createCrunker(trackSrc: string[]) {
    const crunker = new Crunker();
    const concatenatedTrack =  await crunker
      .fetchAudio(...trackSrc)
      .then((buffers: AudioBuffer[]) => crunker.concatAudio(buffers))
      .then((concatenate: AudioBuffer) => {
        const blob = crunker.export(concatenate, 'video/mp4');
        return {
          src: blob.url,
          name: '',
          isPlaying: false,
          order: 1,
        };
      });
    return concatenatedTrack;
  }

The trackSrc is an array of the property src, created via URL.createObjectURL with this function:

private formatAudioFiles(files: FileList): IAudioTrack[] {
    const customFiles: IAudioTrack[] = [];
    for (let i = 0; i < files.length; i++) {
        const src = URL.createObjectURL(files[i]);
        customFiles.push({
          name: files[i].name,
          src,
          isPlaying: false,
          order: i + 1,
        });
      // }
    }
    return customFiles;
  }

And then I read it with another lib which is HowlerJs.
Is this a known problem? Or does it come from my code :D ?

Converting files to buffers manually

Sorry to be coming in with so many questions, but I'm trying to merge files from an array:

const tracks = ["audio1.mp3", "audio2.mp3"];

document.getElementById("option1").onclick = async function() {

try{
    const crunker = new Crunker.default();
    const buffers = await Promise.all(
        Array.from(tracks).map(async (file) => crunker._context.decodeAudioData(await file.arrayBuffer()))
    );
    const merged = await crunker["mergeAudio"](buffers);
    const output = await crunker.export(merged, 'final/mp3');
    await crunker.download(output.blob, "merge");

    document.getElementById("update").innerHTML = "Button Pressed";
}
catch(err) {
    document.getElementById("update").innerHTML = err.message;
}

};

but I'm getting the error:

file.arrayBuffer is not a function.

I tried to follow what happened in the client example, and I don't really know where I'm going wrong.

Expose AudioContext

Hi,

I'm using Crunker in a small rhythm game prototype; I need the current playback time which you can normally get from AudioContext.prototype.getOutputTimestamp, but I'm unable to do this since Crunker isn't exposing the audioContext.

Is it possible to expose this, or against the design philosophy?

Crunker is not a constructor

I'm very new to using external modules, so this is most definitely a fault on my part, but I'm trying to implement the example shown after installing crunker, and I'm getting the error "Crunker is not a constructor". This is a snapshot of the code:

try {
let crunker = new Crunker();
crunker
.fetchAudio('/audio1.mp3', '/audio2.mp3')
.then((buffers) => crunker.mergeAudio(buffers))
.then((merged) => crunker.export(merged, 'final/mp3'))
.then((output) => crunker.download(output.blob))
.catch((error) => {
throw new Error(error);
});
}
catch(err) {
document.getElementById("update").innerHTML = err.message;
}

I'd appreciate any help on this :)

RangeError: Source is too large

I tried to add 15 small (max length 5sec) .mp3 files. After that I got following error. How to solve this error?

Crunker.js:38 Uncaught (in promise) RangeError: Source is too large
    at Float32Array.set (<anonymous>)
    at buffers.map.buffer (Crunker.js:38)
    at Array.map (<anonymous>)
    at Crunker.concatAudio (Crunker.js:37)
    at eval (eval at <anonymous> (bundle.min.js:44), <anonymous>:60:30)

screen shot 2018-03-22 at 12 04 13 pm

size - sampleRate slow motion effect

hi, i am using crunker to merge 2 mp3 audio files (voice and background).
voice.mp3 is 1mb
background.mp3 is 780kb
after merged the files the size of result.mp3 is about 11mb.

I followed the advice to change the sampleRate from 44100 to 22050, but i noticed that the background.mp3 slows down.
I have the impression that it went from 1x to 0.5x
Is there a way to reduce the size of result.mp3 without creating the slow motion effect?
Thanks

Upload data instead of downloading.

Hey, I really want to upload the "crunked" audio file. My application should merge two webm's (which works fine, i've tested it with the downloaded data.)

Is this even possible with crunker? I get errors with REACT.

THanks in advance

React.useEffect(() => {
    if (crunkerRef.current) {
      let audio = new Crunker();
      audio
        .fetchAudio(oldAudioFileUrl, newAudioFileUrl)
        .then(buffers => audio.mergeAudio(buffers))
        .then(merged => audio.export(merged, 'audio/webm'))
        .then(output => { 
//CREATING A base64 string out of the merged buffers so i can upload it. is this even the right place?
          const file_reader = new FileReader();
          const dateOfRecording = Date.now();
          file_reader.readAsDataURL(output.blob);
          file_reader.onloadend = async function() {
            const base64_string = file_reader.result;
            uploadAudio(base64_string, author, chatId, dateOfRecording);
            return base64_string;
          };
          setConsolidatedAudioFileUrl(
            `https://res.cloudinary.com/fiddle/video/upload/${chatId}-${dateOfRecording}-${author}.webm`
          );
          setTimeout(() => {
            sendChatMessage(consolidatedAudioFileUrl, author, type, chatId);
          }, 2000);
          setConsolidationDone(true);
        })
        .catch(error => {
          throw new Error(error);
        });
    }
  }, [
    oldAudioFileUrl,
    newAudioFileUrl,
    author,
    chatId,
    consolidatedAudioFileUrl,
    setConsolidatedAudioFileUrl,
    setConsolidationDone
  ]);

Concatenating buffers results in change of duration?

Hey!

I tried concatenating 3 audio buffers of 17.544 in duration. For some reason, it resulted in a 57.286530612244896 duration audio buffer, instead of 52.632000000000005, any ideas, on why this might have happened? Floating-point problems?

Here is the code sample I used:

const crunker = new Crunker();

const audioBuffersSrc = audioTracks.map(({ audioSrc }) => audioSrc);
const audioBuffers = await crunker.fetchAudio(...audioBuffersSrc);
const audioPlaybackTracks = audioBuffers.reduce((acc, audioBuffer, index) => {
    const { duration } = audioBuffer;
    const prevPlaybackTrack = acc[index - 1] || {};
    const { duration: prevDuration } = prevPlaybackTrack;

    return [
        ...acc,
        {
            duration,
            endTime: prevDuration + duration
        }
    ];
}, []);

const audioBuffer = await crunker.concatAudio(audioBuffers);
console.log(audioBuffer.duration, audioPlaybackTracks);

I looked at the source code, suspecting forceful padding, but found nothing. Any ideas? I need to know the exact length of segments I concatenate.

crunker.play(buffer) error buffer is not defined

Hi there, im stuck at playing audio file, im able to download it, and its great, just can't figure out how to play it.

As well, is it possible to load contacted audio to waveSurfer? Or how can I locate where is concacted audio so I can play it afterwards?

Does any video alternative exists?

Hey team,

I need to play a video (webm) and an audio (m4a) file at the same time on a browser that only accepts one media playing at a time (if I try to play them simultaneously on separate

So I was looking for something for merging those two and found this library but for only audio. Does any video alternative exists?

Is that something that is almost impossible? Because it's been really hard to find anything. But I know that YouTube player does that. It downloads two separate files (video/webm and audio/webm) and merges them into one blob.

Progress Report

Does this library have any kind of event or callback function to report on the progress of a particular concatenation or merge ?

I have a situation where I might need to concatenate many many (like 50+) files, and it would be good to be able to report to the user as the progress moves from 0 to 100% completion.

By extension, the estimated time remaining for completion could also be reported.

Mp3 chunks into a single mp3.

Hi, quick question if that's ok? I've created a voice recording system which splits up a recording into multiple mp3 blobs, could this be used to take chunks of mp3's and then turn them into a single mp3?

Reason I've asked is I've had trouble with other concatenation methods which seems to leave little clicks between each of the chunks when they're appended, and after research I know that mp3's have headers on them which needs to be stripped out etc or concatenation isn't smooth. Would this be a valid use case to use this? Just thought I'd ask before I dive in, although it's probably best just to try this for myself.

Thanks!

Merging files at different times, fade option?

Hi there, I would like to use crunker to merge Piano samples into Piano scores

Would need ability to merge sound samples at different times, is this possible?

Then as well don't want these sounds to play to the end, as most are long well beyond 5 seconds, but I need them to play only for fraction of second, 0.125, 0.25 seconds etc, is it possible to fade out sounds at desired time or could it be possible in any other way?

Not working on Firefox

I am using this dependency to fetch, concatenate, and export all of the mp3 chunks from an m3u file. It works perfectly fine on Chrome, but on Firefox the download just silently fails (no errors). I am on the latest version of Firefox (89.0). According to Tenpi/soundcloud-download#8, someone also reported that the downloads are all .mp3.part (incomplete mp3 files), but I have not reciprocated that personally.

Side note: It would be great if we could also add metadata (such as the song cover) to the download.

Relevant code:

const downloadM3U = async (url, title) => {
  const m3u = await fetch(url).then((r) => r.text())
  const urls = m3u.match(/(http).*?(?=\s)/gm)
  let crunker = new Crunker.default({sampleRate: 48000})
  const buffers = await crunker.fetchAudio(...urls)
  const merged = await crunker.concatAudio(buffers)
  const output = await crunker.export(merged, "audio/mp3")
  await crunker.download(output.blob, title)
  return null
}

Create Typings

Migrate project to Typescript / Flow (personal preference for TypeScript) before publishing as package on npm?

Adding To Project

How do I use this in my html project as in generally you'd do <script src = " "> </script>. However I cant seem to find the link what is the alternative way of doing this? Also its raising an error with export in the js file: Uncaught SyntaxError: Unexpected token 'export'. Sorry for the stupid questions I'm new to all this.

split large audio file [help]

I have successfully used this library for concatenating audio files, but I was wandering if it can be used for splitting files too.

  const reader = new FileReader();
  const blob = file.slice(offset, chunkSize + offset);
  r.onload = readEventHandler;
  r.readAsArrayBuffer(blob);

reading the file in chunks, and then trying to get AudioBuffer in the readEventHandler

const readEventHandler = evt => {
    const arrayBuffer = evt.target.result as ArrayBuffer;
    crunker._context.decodeAudioData(
          arrayBuffer,
          d => console.log(d),
          e => console.log(e)
    );
}

the problem is that only the first part of the file is getting decoded since only it has the necessary headers. For the rest of the parts I am getting
DOMException: Unable to decode audio data.

I tried to manually add the headers to each chunk with modified writeHeaders function , but the audio I get is somehow too fast.

Any suggestions?

const writeHeaders = (arrayBuffer: ArrayBuffer) => {
  // const arrayBuffer = new ArrayBuffer(44 + buffer.length * 2);
  const view = new DataView(arrayBuffer);
  const sampleRate = 44100;

  writeString(view, 0, 'RIFF');
  view.setUint32(4, 32 + arrayBuffer.byteLength * 2, true);
  writeString(view, 8, 'WAVE');
  writeString(view, 12, 'fmt ');
  view.setUint32(16, 16, true);
  view.setUint16(20, 1, true);
  view.setUint16(22, 2, true);
  view.setUint32(24, sampleRate, true);
  view.setUint32(28, sampleRate * 4, true);
  view.setUint16(32, 4, true);
  view.setUint16(34, 16, true);
  writeString(view, 36, 'data');
  view.setUint32(40, arrayBuffer.byteLength * 2, true);

  return floatTo16BitPCM(view, arrayBuffer, 44);
};

Embedding Url

<audio src="example.mp3" id = 'ex'></audio>
<audio src="example1.mp3" id = 'ex1'></audio>
var f = document.getElementById('ex').src
var f1 = document.getElementById('ex1').src

Whenever I do:

audio
    .fetchAudio("f", "f1")

it says it cant seem to find the file, even though Im calling the URl.

fetchAudio parameters as an array

It would be extermely useful to be able to pass an array of song urls to fetchAudio instead of separate parameters. So in addition to

crunker.fetchAudio(songURL, anotherSongURL)

an option to pass song urls like this

crunker.fetchAudio(arrayOfSongURLs)

would make a lot of sense in my opinion, for example in situations where the song urls are generated dynamically and we don't know how many of them there will be etc.

Edit: Yes I know this can be done for example using spread operator but anyways it would be nice to have this option.

Failed to load because no supported source was found

Hi, When merge two audios and use the result into a html audio element i got this error.
The result happen when the audio result is greater than 1 minute ...and only in some android devices (chrome)
Have you got an idea?...when i made a merge with less than 1 minute (the same audios) it worked

            audio.fetchAudio(audio1,
                    audio2
                    )
                    .then(buffers => audio.merge(buffers))
                    .then(merged => audio.export(merged, 'audio/mp3'))
                    .then(output => {
                        $('#audio')[0].src = output.url;
                        $('#audio')[0].play();
                    });

int the _maxDuration function i changed the return

return Math.min(Math.min.apply(Math, buffers.map(buffer => buffer.duration)), (is_android ? 60 : 1000));

to return only 1 minute video....but this is not what i need (i need the complete audio)

please help

thanks a lot

Blob size

I tried output audio with concatAudio function return value.
Blob size is always 4 x concatBufferSize.
is there any method to compress mp3 file size?
Best

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.