Book a call
Menu

Why Chrome Renamed Our .m4a to .mp4: Saving Recordings Properly With chrome.downloads

Happy Coders team4 Dec 202614 min read
Why Chrome Renamed Our .m4a to .mp4: Saving Recordings Properly With chrome.downloads

The HappyRec extension for Chrome and Edge records voice notes as well as screens. One of the voice formats is M4A: AAC audio in an MP4 container, the format phones and music players are happy with. Saved the obvious way through the browser’s download manager, it arrives in the Downloads folder as Happy Recorder Voice 2026-… .mp4. Same bytes, wrong extension, and an operating system that picks applications by extension now treats a voice note as a video.

The fix is one line. The reasons behind it, and everything else we learned while turning a Blob from MediaRecorder into a file that a user can find, open and delete, take longer to explain. This post walks through the whole save path of the extension: how it picks a container, how a MIME type becomes an extension, why chrome.downloads.download needs a careful wrapper, and how a “recent recordings” list stays honest when the user moves files behind its back.

There is no server, so the download manager is the file system

A browser extension cannot write files wherever it likes. The HappyRec extension has no backend and no account, by design, so there is nowhere to upload to either. That leaves one sanctioned way to put a file on the user’s disk: chrome.downloads. The recording becomes an object URL, the object URL becomes a download, and the download manager writes it into the user’s Downloads folder, under a Happy Recorder/ subfolder.

That decision shapes everything else. The download manager decides the final filename. It decides what to do about name collisions. It owns the Save dialog. It knows whether a file still exists. Our job is mostly to give it the right inputs and to listen carefully to what it tells us back. The manifest asks for exactly the two permissions this needs:

"permissions": [
  ...
  "downloads",
  "downloads.open",
  ...
]

downloads.open is separate from downloads because opening a file with the system’s default application is more sensitive than saving one, and Chrome gates it behind its own permission and a user gesture. We come back to that below.

Step one: choosing a container the browser can actually write

Before a recording starts, the extension has to pick a MIME type for MediaRecorder. Browsers differ, versions differ, and asking for something unsupported throws. So the extension keeps an ordered ladder of candidates and takes the first one that MediaRecorder.isTypeSupported accepts:

const VIDEO_TYPES = {
  mp4: [
    'video/mp4;codecs="avc1.640028,mp4a.40.2"',
    'video/mp4;codecs="avc1.42E01E,mp4a.40.2"',
    'video/mp4;codecs="avc1,mp4a.40.2"',
    'video/mp4;codecs="avc1,opus"',
    'video/mp4',
  ],
  webm: [
    'video/webm;codecs="vp9,opus"',
    'video/webm;codecs="vp8,opus"',
    'video/webm',
  ],
};

const AUDIO_TYPES = {
  m4a: ['audio/mp4;codecs="mp4a.40.2"', 'audio/mp4'],
  webm: ['audio/webm;codecs=opus', 'audio/webm'],
};

function firstSupported(candidates) {
  if (typeof MediaRecorder === 'undefined') return null;
  return candidates.find((type) => MediaRecorder.isTypeSupported(type)) || null;
}

export function videoMimeFor(containerPref) {
  const mp4 = firstSupported(VIDEO_TYPES.mp4);
  const webm = firstSupported(VIDEO_TYPES.webm);
  if (containerPref === 'webm') return webm || mp4;
  return mp4 || webm;
}

Recent Chrome and Edge on macOS and Windows accept H.264 with AAC in MP4, so with the default setting (“Auto (MP4 when available)”) that is what users get. MP4 is the format that opens with the fewest questions once the file leaves the computer, which matters for a tool whose output is usually sent to someone else. If the browser cannot write MP4, the ladder falls through to VP9 with Opus in WebM, then VP8, then plain WebM. The user can also force WebM in Preferences, which simply swaps the order.

Two details are worth copying. First, every candidate in the MP4 list carries an explicit codec string, from a specific H.264 profile down to a bare video/mp4, so a browser that accepts only some combinations still lands on something it can do. Second, the function never returns a type the browser rejected; the worst case is null, and the session turns that into a readable error (“cannot encode video in any supported format on this computer”) instead of letting new MediaRecorder throw a bare NotSupportedError.

The same check drives the interface. The recorder only shows the M4A voice pill when audio/mp4 is supported, and Preferences shows “This browser can’t write MP4, so recordings are saved as WebM either way” only when that is true. A setting the browser cannot honour is never offered.

Step two: from MIME type to file extension

When recording stops, we know the MIME type the recorder actually used (recorder.mimeType, which can be more specific than what we asked for). The file extension is derived from the base type, ignoring codec parameters:

export function extensionForMime(mime) {
  const base = (mime || '').split(';')[0].trim();
  switch (base) {
    case 'video/mp4': return 'mp4';
    case 'video/webm': return 'webm';
    case 'video/x-matroska': return 'mkv';
    case 'audio/mp4': return 'm4a';
    case 'audio/webm': return 'webm';
    case 'audio/wav': return 'wav';
    default: return base.startsWith('audio/') ? 'audio' : 'video';
  }
}

Note the audio/mp4 case. AAC audio in an MP4 container is, by convention, an .m4a file. Players, phones and operating systems use that extension to decide that this is music or a voice note rather than a video. So we ask for Happy Recorder Voice 2026-12-04 at 16.44.10.m4a. The download manager has other ideas.

From MediaRecorder blob to a file in Downloads
Each step hands the next one something it agrees with.

Why Chrome renamed our .m4a to .mp4

Chrome’s download manager does not take a requested filename entirely at face value. When the extension in the requested name does not match the MIME type of the content, it may replace the extension with the one it associates with that MIME type. For audio/mp4, the extension it pairs with is .mp4. Our blob was labelled audio/mp4, because that is what MediaRecorder reported, so our carefully chosen .m4a came out as .mp4.

There are a few ways to argue with that, and most are bad. Renaming the file after the download would need file system access the extension does not have. Lying in the other direction, labelling the blob application/octet-stream, risks a different rename and loses the type information entirely. The tidy answer is to give the blob a MIME type whose conventional extension is .m4a. audio/x-m4a is exactly that, and the bytes do not change at all. A Blob is immutable and cheap to re-wrap, so this is a constructor call, not a copy of the audio:

const ext = extensionForMime(type);
const requestedName = `${FOLDER}/${recordingFileStem(!!isAudio)}.${ext}`;
// Chrome's download manager replaces an extension that does not match the
// blob's MIME type, and it pairs audio/mp4 with ".mp4". Re-label AAC voice
// notes as audio/x-m4a (the same bytes) so the file keeps its ".m4a" name.
const downloadBlob = ext === 'm4a' && /^audio\/mp4/i.test(blob.type || type)
  ? new Blob([blob], { type: 'audio/x-m4a' })
  : blob;
const url = URL.createObjectURL(downloadBlob);
let outcome;
try {
  outcome = await downloadAndWait({
    url,
    filename: requestedName,
    saveAs: !!askWhereToSave,
    conflictAction: 'uniquify',
  });
} finally {
  URL.revokeObjectURL(url);
}
if (!outcome) return null;   // user cancelled the Save dialog

The condition is deliberately narrow. Only voice notes whose extension resolved to m4a and whose type is audio/mp4 are re-labelled. Video MP4 files, WebM and WAV pass through untouched, because for those the MIME type and the extension already agree.

Two other options in that call are doing quiet work. conflictAction: 'uniquify' tells the download manager to append a number rather than overwrite or prompt when a file of that name exists, so a user who records twice in the same second does not lose the first file. saveAs is driven by the user’s “Ask where to save each recording” preference, which is off by default; the “Save a copy…” button after a recording passes true unconditionally.

The quirk M4A still has

Getting the extension right did not make M4A the default voice format, and the reason is worth knowing if you record audio with MediaRecorder. Chrome’s audio-only MP4 output is fragmented, and the duration written in its header can be shorter than the recording. All of the audio is present, and decoding the file yields the full length, but a player that trusts the header shows the wrong duration and may not let you seek to the end. WebM and WAV do not have this problem. So WAV (written from raw PCM, since MediaRecorder cannot produce it) is the default voice format, and M4A is listed last for people who want it specifically.

Step three: waiting for a download properly

chrome.downloads.download resolves with a download id as soon as the download starts, not when it finishes. For a recording that is not good enough. We want to tell the user the file is saved only once it is, we want to show a human message if it fails, and we must not revoke the object URL while the download manager is still reading from it. So the call is wrapped in a function that resolves only on a terminal state:

function downloadAndWait(options) {
  return new Promise((resolve, reject) => {
    let downloadId = null;
    let settled = false;
    let timer = null;
    const seen = new Map();

    const finish = (fn, value) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      chrome.downloads.onChanged.removeListener(onChanged);
      fn(value);
    };

    const judge = (info) => {
      if (info.state === 'complete') {
        finish(resolve, { downloadId });
      } else if (info.state === 'interrupted') {
        if (info.error === 'USER_CANCELED') finish(resolve, null);
        else finish(reject, new Error(humanDownloadError(info.error)));
      }
    };

    function onChanged(delta) {
      const info = seen.get(delta.id) || {};
      if (delta.state) info.state = delta.state.current;
      if (delta.error) info.error = delta.error.current;
      seen.set(delta.id, info);
      if (downloadId !== null && delta.id === downloadId) judge(info);
    }

    chrome.downloads.onChanged.addListener(onChanged);
    timer = setTimeout(() => finish(reject, new Error(humanDownloadError('TIMEOUT'))),
                       DOWNLOAD_TIMEOUT_MS);   // 10 minutes

    Promise.resolve(chrome.downloads.download(options)).then((id) => {
      downloadId = id;
      if (seen.has(id)) judge(seen.get(id));
    }).catch((error) => {
      const message = (error && error.message) || String(error);
      // Older Chrome versions reject instead of reporting USER_CANCELED.
      if (/cancel/i.test(message)) finish(resolve, null);
      else finish(reject, new Error(`could not save the recording: ${message}`));
    });
  });
}

There is a race hidden in the obvious version of this. If you call download(), wait for the id, and then add an onChanged listener, a small file can complete before your listener exists, and you wait forever. The wrapper registers the listener first. Deltas that arrive before the id is known are buffered in the seen map, keyed by download id, and judged as soon as the id comes back.

The outcomes are split three ways, because the caller needs to treat them differently:

  • Complete resolves with the id.
  • Cancelled resolves with null. A user closing the Save dialog is a decision, not an error, and should not produce a red banner. Newer versions report this as an interrupted download with USER_CANCELED; older versions reject the download() promise instead, so both paths are handled.
  • Anything else rejects with a sentence a person can act on.

Those sentences come from a small mapping of the download manager’s error codes:

function humanDownloadError(code) {
  switch (code) {
    case 'FILE_ACCESS_DENIED':
      return `${shortBrowserName()} was not allowed to write to the Downloads folder.`;
    case 'FILE_NO_SPACE':
      return 'There is not enough free disk space to save the recording.';
    case 'FILE_TOO_LARGE':
      return 'The recording is too large for the destination disk.';
    case 'FILE_BLOCKED':
    case 'FILE_SECURITY_CHECK_FAILED':
    case 'FILE_VIRUS_INFECTED':
      return `${shortBrowserName()} blocked the file — check its download settings.`;
    case 'TIMEOUT':
      return 'Saving took too long and was abandoned.';
    default:
      return `${shortBrowserName()} could not save the recording (${code || 'unknown error'}).`;
  }
}

“There is not enough free disk space to save the recording” is far more useful at the end of a forty-minute recording than FILE_NO_SPACE. The ten-minute timeout exists so a download that never reaches a terminal state cannot leave the recorder window waiting for good.

Only after the promise settles does the finally block revoke the object URL. Revoke it early and the download fails part-way; never revoke it and every recording stays pinned in memory until the window closes.

Step four: remembering what was saved

The Mac app can list recordings by scanning its save folder. An extension cannot scan folders, so the “Recent recordings” list is a small piece of metadata kept in chrome.storage.local, newest first and capped at 50 entries. The important design decision is where the filename in each entry comes from: not from what we asked for, but from what the download manager reports it actually wrote.

let item = null;
try {
  item = await searchById(outcome.downloadId);
} catch {
  item = null;
}
const filename = (item && item.filename) || requestedName;
const entry = {
  id: crypto.randomUUID(),
  downloadId: outcome.downloadId,
  filename,
  title: titleFrom(filename),
  date: Date.now(),
  durationMs: Math.max(0, Math.round(durationMs || 0)),
  isAudio: !!isAudio,
  mime: type,
  bytes: blob.size,
  width: width || 0,
  height: height || 0,
};
const entries = await readEntries();
await writeEntries([entry, ...entries.filter((e) => e.downloadId !== entry.downloadId)]);

The final name can differ from the requested one in at least three ways: uniquify added a number, the user typed a different name in the Save dialog, or the user picked a different folder. Reading item.filename back via chrome.downloads.search means the list shows the file the user will actually find. If the lookup fails, the requested name is a reasonable fallback, and the save is still a success.

Entries are keyed on the download id, not the filename. That id is what every later operation needs: opening, revealing in Finder or Explorer, deleting.

Keeping the list honest

Users move and delete files. They clear their download history. A list that only ever grows soon lies. So every time the list is shown, each entry is checked against the download manager:

export async function listRecordings() {
  const entries = await readEntries();
  if (entries.length === 0) return [];
  let items;
  try {
    items = await Promise.all(entries.map((entry) => searchById(entry.downloadId)));
  } catch {
    // The downloads API is unavailable for some reason — show what we have.
    return entries.map((entry) => ({ ...entry, exists: true }));
  }
  const kept = [];
  let dropped = false;
  entries.forEach((entry, i) => {
    const item = items[i];
    if (!item) {
      dropped = true;      // erased from the browser's download history
      return;
    }
    kept.push({ ...entry, exists: item.exists !== false && item.state === 'complete' });
  });
  if (dropped) {
    await writeEntries(kept.map(({ exists, ...rest }) => rest));
  }
  return kept;
}

There are two kinds of stale entry, and they get different treatment.

  • The download item is gone, usually because the user cleared their download history. The extension can no longer open, reveal or delete that file, so the entry is dropped from storage. The file itself is untouched on disk.
  • The item exists but the file does not, because the user moved or deleted it. The row stays, marked “File missing”, so the user understands why clicking it does nothing, and can remove it from the list.

Deleting from the list calls chrome.downloads.removeFile, then chrome.downloads.erase to forget the item, then removes the entry. Each step tolerates the thing already being gone. The confirmation text changes too: “The file is removed from your Downloads folder” when the file exists, a plain “Remove from the list?” when it does not.

How the recordings list treats each state of a saved file
The list is checked against the download manager every time it is shown.

When the recorder itself refuses the format

isTypeSupported answering yes is a strong hint, not a guarantee. A browser can still refuse to construct a MediaRecorder with a type it claimed to support, for example because of a hardware encoder that disappears between the check and the start. The extension does not let that surface as a raw exception. Construction is wrapped, and the two failure shapes get different messages: a NotSupportedError becomes “cannot record in the format … Choose a different format in Settings”, which points the user at the one thing they can change, and anything else becomes “Could not start the recorder” with the underlying message attached for the support conversation.

Encoder errors during recording are routed the same way, through the recorder’s onerror handler, into a single failure path that records the message, reports it once, and hands the ending to the recorder window, which shows a sentence instead of a stack trace. The principle is the same one as the download error mapping: every place where the browser can say no is a place where the user deserves a sentence they can act on, and a place where the recording session must end cleanly rather than half-alive.

WebM output has one more step on the way to the download manager. Chrome’s WebM files are written without a duration in their header, so before saving, the extension patches the duration in, using the length it measured itself. That step is covered in detail in our earlier post on WebM durations; here it only matters that it happens before the blob is handed to saveRecording, so the file on disk is complete the moment the download finishes.

Opening a file needs a user gesture

chrome.downloads.open launches the file with the system’s default application, and Chrome only allows it in direct response to a user action. An await before the call is enough to lose the gesture. So the open function is called synchronously from the click handler, and it treats a refusal as an ordinary outcome rather than an exception:

/// Opens the file with the system's default player. downloads.open needs a
/// user gesture, so this must be called synchronously from a click handler.
export function openRecording(entry) {
  try {
    const result = chrome.downloads.open(entry.downloadId);
    if (result && typeof result.then === 'function') {
      return result.then(() => true, () => false);
    }
    return Promise.resolve(true);
  } catch {
    return Promise.resolve(false);
  }
}

This is also why the correct extension matters beyond cosmetics. downloads.open hands the file to the operating system, and the operating system chooses an application by extension. An .mp4 voice note opens in a video player with a black frame; an .m4a opens in whatever the user uses for audio.

What to take from this

  • Pick a MediaRecorder type from an ordered ladder with isTypeSupported, and only offer settings the current browser can honour.
  • Derive the extension from the MIME type, then make sure the MIME type you hand to the download manager agrees with that extension. audio/x-m4a keeps .m4a files named .m4a.
  • Wrap chrome.downloads.download so it settles on complete, cancelled or failed, register the change listener before starting, and revoke the object URL only afterwards.
  • Store the filename the download manager reports, keyed by download id, and reconcile the list against downloads.search every time it is shown.
  • Call downloads.open synchronously from the click.

None of this is glamorous, but it is the difference between “I recorded it” and “I sent it, and it opened”.

HappyRec is our free screen recorder for Mac and Windows, with a Chrome and Edge extension for recording from the browser. See what it does.

Keep reading

Related articles