Add framesToDuration helper

This commit is contained in:
Rob Watson 2022-01-15 09:34:56 +01:00
parent ed964cb58f
commit d8173cdace
2 changed files with 40 additions and 0 deletions

View File

@ -0,0 +1,29 @@
import framesToDuration from './framesToDuration';
describe('framesToDuration', () => {
it('returns the expected result for 0 frames at 44100hz', () => {
expect(framesToDuration(0, 44100)).toEqual({ seconds: 0, nanos: 0 });
});
it('returns the expected result for 44100 frames at 44100hz', () => {
expect(framesToDuration(44100, 44100)).toEqual({ seconds: 1, nanos: 0 });
});
it('returns the expected result for 88200 frames at 44100hz', () => {
expect(framesToDuration(88200, 44100)).toEqual({ seconds: 2, nanos: 0 });
});
it('returns the expected result for 88201 frames at 44100hz', () => {
expect(framesToDuration(88201, 44100)).toEqual({
seconds: 2,
nanos: 22675,
});
});
it('returns the expected result for 110250 frames at 44100hz', () => {
expect(framesToDuration(110250, 44100)).toEqual({
seconds: 2,
nanos: 500_000_000,
});
});
});

View File

@ -0,0 +1,11 @@
import { Duration } from '../generated/google/protobuf/duration';
function framesToDuration(frames: number, sampleRate: number): Duration {
const secs = Math.floor(frames / sampleRate);
const nanos = Math.floor(
((frames % sampleRate) / sampleRate) * 1_000_000_000
);
return { seconds: secs, nanos: nanos };
}
export default framesToDuration;