• Contact Us
  • Privacy Policy
  • Terms of Use
  • DMCA
  • Disclaimer
Sunday, July 14, 2024
CryptoBangs.com
Advertisement
  • Home
  • Live Crypto Prices
  • Crypto News
    • Bitcoin
    • Ethereum
    • Ripple
    • Altcoin
    • NFT News
  • DeFi
  • Blockchain
  • Regulation
  • Shop
  • Blog
  • Calculator
No Result
View All Result
  • Home
  • Live Crypto Prices
  • Crypto News
    • Bitcoin
    • Ethereum
    • Ripple
    • Altcoin
    • NFT News
  • DeFi
  • Blockchain
  • Regulation
  • Shop
  • Blog
  • Calculator
No Result
View All Result
CryptoBangs.com
No Result
View All Result

Building Real-Time Language Translation with AssemblyAI and DeepL in JavaScript

July 14, 2024
in Blockchain
Reading Time: 4 mins read
A A
Building Real-Time Language Translation with AssemblyAI and DeepL in JavaScript
ShareShareShareShareShare

Related articles

NVIDIA Grace CPU Enhances Mathematical Optimization Efficiency and Performance

NVIDIA Grace CPU Enhances Mathematical Optimization Efficiency and Performance

July 13, 2024
Top Trending Cryptos on Solana Chain Today – Cost Hot Dog, Pickle Rick, Hump

Top Trending Cryptos on Solana Chain Today – Cost Hot Dog, Pickle Rick, Hump

July 13, 2024


Ted Hisokawa
Jul 14, 2024 05:20

Learn how to create a real-time language translation service using AssemblyAI and DeepL in JavaScript. Step-by-step guide for developers.





In a comprehensive tutorial, AssemblyAI offers insights into creating a real-time language translation service using JavaScript. The tutorial leverages AssemblyAI for real-time speech-to-text transcription and DeepL for translating the transcribed text into various languages.

Introduction to Real-Time Translation

Translations play a critical role in communication and accessibility across different languages. For instance, a tourist in a foreign country may struggle to communicate if they don’t understand the local language. AssemblyAI’s Streaming Speech-to-Text service can transcribe speech in real-time, which can then be translated using DeepL, making communication seamless.

Setting Up the Project

The tutorial begins with setting up a Node.js project. Essential dependencies are installed, including Express.js for creating a simple server, dotenv for managing environment variables, and the official libraries for AssemblyAI and DeepL.

mkdir real-time-translation
cd real-time-translation
npm init -y
npm install express dotenv assemblyai deepl-node

API keys for AssemblyAI and DeepL are stored in a .env file to keep them secure and avoid exposing them in the frontend.

Creating the Backend

The backend is designed to keep API keys secure and generate temporary tokens for secure communication with the AssemblyAI and DeepL APIs. Routes are defined to serve the frontend and handle token generation and text translation.

const express = require("express");
const deepl = require("deepl-node");
const { AssemblyAI } = require("assemblyai");
require("dotenv").config();

const app = express();
const port = 3000;

app.use(express.static("public"));
app.use(express.json());

app.get("https://blockchain.news/", (req, res) => {
  res.sendFile(__dirname + "/public/index.html");
});

app.get("/token", async (req, res) => {
  const token = await client.realtime.createTemporaryToken({ expires_in: 300 });
  res.json({ token });
});

app.post("/translate", async (req, res) => {
  const { text, target_lang } = req.body;
  const translation = await translator.translateText(text, "en", target_lang);
  res.json({ translation });
});

app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

Frontend Development

The frontend consists of an HTML page with text areas for displaying the transcription and translation, and a button to start and stop recording. The AssemblyAI SDK and RecordRTC library are utilized for real-time audio recording and transcription.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Voice Recorder with Transcription</title>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body>
    <div class="min-h-screen flex flex-col items-center justify-center bg-gray-100 p-4">
      <div class="w-full max-w-6xl bg-white shadow-md rounded-lg p-4 flex flex-col md:flex-row space-y-4 md:space-y-0 md:space-x-4">
        <div class="flex-1">
          <label for="transcript" class="block text-sm font-medium text-gray-700">Transcript</label>
          <textarea id="transcript" rows="20" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm"></textarea>
        </div>
        <div class="flex-1">
          <label for="translation" class="block text-sm font-medium text-gray-700">Translation</label>
          <select id="translation-language" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm">
            <option value="es">Spanish</option>
            <option value="fr">French</option>
            <option value="de">German</option>
            <option value="zh">Chinese</option>
          </select>
          <textarea id="translation" rows="18" class="mt-1 block w-full p-2 border border-gray-300 rounded-md shadow-sm"></textarea>
        </div>
      </div>
      <button id="record-button" class="mt-4 px-6 py-2 bg-blue-500 text-white rounded-md shadow">Record</button>
    </div>
    <script src="https://www.unpkg.com/assemblyai@latest/dist/assemblyai.umd.min.js"></script>
    <script src="https://www.WebRTC-Experiment.com/RecordRTC.js"></script>
    <script src="main.js"></script>
  </body>
</html>

Real-Time Transcription and Translation

The main.js file handles the audio recording, transcription, and translation. The AssemblyAI real-time transcription service processes the audio, and the DeepL API translates the final transcriptions into the selected language.

const recordBtn = document.getElementById("record-button");
const transcript = document.getElementById("transcript");
const translationLanguage = document.getElementById("translation-language");
const translation = document.getElementById("translation");

let isRecording = false;
let recorder;
let rt;

const run = async () => {
  if (isRecording) {
    if (rt) {
      await rt.close(false);
      rt = null;
    }
    if (recorder) {
      recorder.stopRecording();
      recorder = null;
    }
    recordBtn.innerText = "Record";
    transcript.innerText = "";
    translation.innerText = "";
  } else {
    recordBtn.innerText = "Loading...";
    const response = await fetch("/token");
    const data = await response.json();
    rt = new assemblyai.RealtimeService({ token: data.token });
    const texts = {};
    let translatedText = "";
    rt.on("transcript", async (message) => {
      let msg = "";
      texts[message.audio_start] = message.text;
      const keys = Object.keys(texts);
      keys.sort((a, b) => a - b);
      for (const key of keys) {
        if (texts[key]) {
          msg += ` ${texts[key]}`;
        }
      }
      transcript.innerText = msg;
      if (message.message_type === "FinalTranscript") {
        const response = await fetch("/translate", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            text: message.text,
            target_lang: translationLanguage.value,
          }),
        });
        const data = await response.json();
        translatedText += ` ${data.translation.text}`;
        translation.innerText = translatedText;
      }
    });
    rt.on("error", async (error) => {
      console.error(error);
      await rt.close();
    });
    rt.on("close", (event) => {
      console.log(event);
      rt = null;
    });
    await rt.connect();
    navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then((stream) => {
        recorder = new RecordRTC(stream, {
          type: "audio",
          mimeType: "audio/webm;codecs=pcm",
          recorderType: StereoAudioRecorder,
          timeSlice: 250,
          desiredSampRate: 16000,
          numberOfAudioChannels: 1,
          bufferSize: 16384,
          audioBitsPerSecond: 128000,
          ondataavailable: async (blob) => {
            if (rt) {
              rt.sendAudio(await blob.arrayBuffer());
            }
          },
        });
        recorder.startRecording();
        recordBtn.innerText = "Stop Recording";
      })
      .catch((err) => console.error(err));
  }
  isRecording = !isRecording;
};
recordBtn.addEventListener("click", () => {
  run();
});

Conclusion

This tutorial demonstrates how to build a real-time language translation service using AssemblyAI and DeepL in JavaScript. Such a tool can significantly enhance communication and accessibility for users in different linguistic contexts. For more detailed instructions, visit the original AssemblyAI tutorial.

Image source: Shutterstock


Credit: Source link

ShareTweetSendPinShare
Previous Post

Bullish Bitcoin Indicator Which Led To A Reversal Has Returned, Is $70,000 Possible?

Related Posts

NVIDIA Grace CPU Enhances Mathematical Optimization Efficiency and Performance

NVIDIA Grace CPU Enhances Mathematical Optimization Efficiency and Performance

July 13, 2024

Rongchai Wang Jul 13, 2024 17:50 NVIDIA Grace CPU shows significant improvements in mathematical optimization performance...

Top Trending Cryptos on Solana Chain Today – Cost Hot Dog, Pickle Rick, Hump

Top Trending Cryptos on Solana Chain Today – Cost Hot Dog, Pickle Rick, Hump

July 13, 2024

Join Our Telegram channel to stay up to date on breaking news coverage Investors anticipate a potential reversal in price...

6 Best Meme Coin Presales to Buy Now – Next 10X Cryptos to Explode

6 Best Meme Coin Presales to Buy Now – Next 10X Cryptos to Explode

July 13, 2024

Join Our Telegram channel to stay up to date on breaking news coverage Meme coins have become a hot topic...

Quantum Computing Set to Revolutionize Chemistry Research

Quantum Computing Set to Revolutionize Chemistry Research

July 13, 2024

Darius Baruo Jul 13, 2024 08:26 IBM Research explores quantum computing's potential to transform chemistry, materials,...

6 Best Altcoins to Invest In Now – Maker, ConstitutionDAO, Telcoin, Kaspa

6 Best Altcoins to Invest In Now – Maker, ConstitutionDAO, Telcoin, Kaspa

July 13, 2024

Join Our Telegram channel to stay up to date on breaking news coverage Our spotlight is on the best altcoins...

Load More

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Binance Introduces Word of the Day Game with 500,000 Points Pool

Binance Introduces Word of the Day Game with 500,000 Points Pool

July 8, 2024
Chances of Dogecoin Hitting $1 Before 2030

Chances of Dogecoin Hitting $1 Before 2030

July 11, 2024
Pyth Network introduces Express Relay, aiming to reduce MEV in DeFi

Pyth Network introduces Express Relay, aiming to reduce MEV in DeFi

July 11, 2024
OpenAI and Los Alamos National Laboratory Forge Research Partnership

OpenAI and Los Alamos National Laboratory Forge Research Partnership

July 12, 2024
Forbes Updates Its Price Prediction For SHIB

Forbes Updates Its Price Prediction For SHIB

July 9, 2024
CryptoBangs.com

CryptoBangs.com is an online news portal that aims to share the latest crypto news, bitcoin, altcoin, blockchain, nft news and much more stuff like that.

What’s New Here!

  • Building Real-Time Language Translation with AssemblyAI and DeepL in JavaScript
  • Bullish Bitcoin Indicator Which Led To A Reversal Has Returned, Is $70,000 Possible?
  • TRUMP Meme Coin Soars After Attack on Former US President
  • 7 Years In, Lots Of Work Ahead

Newsletter

Don't miss a beat and stay up to date with our Newsletter!
Loading

  • Contact Us
  • Privacy Policy
  • Terms of Use
  • DMCA
  • Disclaimer

© 2023 - CryptoBangs.com - All Rights Reserved!

No Result
View All Result
  • Home
  • Live Crypto Prices
  • Crypto News
    • Bitcoin
    • Ethereum
    • Ripple
    • Altcoin
    • NFT News
  • DeFi
  • Blockchain
  • Regulation
  • Shop
  • Blog
  • Calculator

© 2018 JNews by Jegtheme.

  • bitcoinBitcoin(BTC)$59,749.003.24%
  • ethereumEthereum(ETH)$3,188.421.90%
  • tetherTether(USDT)$1.00-0.03%
  • binancecoinBNB(BNB)$536.730.58%
  • solanaSolana(SOL)$145.064.31%
  • usd-coinUSDC(USDC)$1.000.02%
  • staked-etherLido Staked Ether(STETH)$3,189.181.96%
  • rippleXRP(XRP)$0.528.60%
  • the-open-networkToncoin(TON)$7.34-0.22%
  • dogecoinDogecoin(DOGE)$0.1139765.67%
  • cardanoCardano(ADA)$0.4364945.67%
  • tronTRON(TRX)$0.1398651.18%
  • avalanche-2Avalanche(AVAX)$26.090.71%
  • shiba-inuShiba Inu(SHIB)$0.0000174.95%
  • wrapped-bitcoinWrapped Bitcoin(WBTC)$59,702.002.93%
  • polkadotPolkadot(DOT)$6.242.53%
  • chainlinkChainlink(LINK)$13.092.40%
  • bitcoin-cashBitcoin Cash(BCH)$376.840.53%
  • uniswapUniswap(UNI)$8.210.95%
  • nearNEAR Protocol(NEAR)$5.374.43%
  • leo-tokenLEO Token(LEO)$5.821.20%
  • daiDai(DAI)$1.00-0.04%
  • litecoinLitecoin(LTC)$70.240.68%
  • matic-networkPolygon(MATIC)$0.534.75%
  • Wrapped eETHWrapped eETH(WEETH)$3,321.991.74%
  • kaspaKaspa(KAS)$0.1686110.27%
  • internet-computerInternet Computer(ICP)$8.7518.18%
  • PepePepe(PEPE)$0.0000092.57%
  • Ethena USDeEthena USDe(USDE)$1.000.02%
  • ethereum-classicEthereum Classic(ETC)$22.454.35%
  • aptosAptos(APT)$6.444.78%
  • fetch-aiArtificial Superintelligence Alliance(FET)$1.19-0.08%
  • stellarStellar(XLM)$0.1008549.50%
  • moneroMonero(XMR)$157.10-1.60%
  • hedera-hashgraphHedera(HBAR)$0.0730638.66%
  • makerMaker(MKR)$2,708.425.89%
  • blockstackStacks(STX)$1.691.82%
  • crypto-com-chainCronos(CRO)$0.0918584.08%
  • filecoinFilecoin(FIL)$4.294.47%
  • cosmosCosmos Hub(ATOM)$6.221.42%
  • render-tokenRender(RNDR)$6.160.08%
  • vechainVeChain(VET)$0.0294529.35%
  • mantleMantle(MNT)$0.733.90%
  • okbOKB(OKB)$39.494.25%
  • arbitrumArbitrum(ARB)$0.700.66%
  • immutable-xImmutable(IMX)$1.364.73%
  • Renzo Restaked ETHRenzo Restaked ETH(EZETH)$3,228.661.79%
  • injective-protocolInjective(INJ)$20.674.36%
  • suiSui(SUI)$0.773.05%
  • First Digital USDFirst Digital USD(FDUSD)$1.000.06%
WP Twitter Auto Publish Powered By : XYZScripts.com