Next.js Discord

Discord Forum

I cannot play mp3 sound because the base path of localization

Answered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
I have a mp3 file "bgm-cute-mp3" in public/audio folder.
var audio = new Audio("/audio/bgm-cute.mp3");
audio.play();

I cannot play the sound and the error message show I am getting the mp3 from "/en/audio/bgm-cute.mp3"

I have implement the localization in my web so the basepath is started the "/en".
Answered by joulev
if so, simply whitelist the mp3 link from middleware i18n handling, like
if (request.nextUrl.pathname.endsWith(".mp3"))
  return NextResponse.next();

// do i18n things
View full answer

9 Replies

Alligator mississippiensisOP
I have a mp3 file "bgm-cute-mp3" in public/audio folder.
var audio = new Audio("/audio/bgm-cute.mp3");
audio.play();

I cannot play the sound and the error message show I am getting the mp3 from
"/en/audio/bgm-cute.mp3"


I have implement the localization in my web so the basepath is started the "/en".

my app structure:
Alligator mississippiensisOP
I fixed by making a new folder call 'en'
and put my audio in /en/audio/
if so, simply whitelist the mp3 link from middleware i18n handling, like
if (request.nextUrl.pathname.endsWith(".mp3"))
  return NextResponse.next();

// do i18n things
Answer
Alligator mississippiensisOP
@joulev
thank you!
I handle in middleware, then I added those whitelist in my middle. it works.
export function middleware(request: NextRequest) {
  const pathname = request.nextUrl.pathname;

  // // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
  // // If you have one
  if (
    [
      '/manifest.json',
      '/favicon.ico',
      // Your other files in `public`
    ].includes(pathname)
  ) {
    return;
  }

  if (request.nextUrl.pathname.endsWith(".mp3")) {
    return NextResponse.next();
  }

  // Check if there is any supported locale in the pathname
  const pathnameIsMissingLocale = i18n.locales.every(
    (locale) =>
      !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
  );

  // Redirect if there is no locale
  if (pathnameIsMissingLocale) {
    const locale = getLocale(request);

    // e.g. incoming request is /products
    // The new URL is now /en-US/products
    return NextResponse.redirect(
      new URL(
        `/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`,
        request.url,
      ),
    );
  }
}
@joulev You could put the file name in the “your other files in public” part, that will work too
Alligator mississippiensisOP
I tried, it seem that my path was not correct.
if I have /public/audio/bgm-cute.mp3

what should I put in the "your other files in public" ?
@joulev Remove the “/public”. should be “/audio/…”
Alligator mississippiensisOP
I see, thanks