laravel localization

laravel localization

In this comprehensive tutorial, learn how to seamlessly integrate voice-to-text functionality into your Laravel application using the powerful Web Speech API. Follow our step-by-step guide to enhance user experience and accessibility with cutting-edge speech recognition technology.

Step 1: Set up a new Laravel Project

composer create-project --prefer-dist laravel/laravel voice-to-text-app
cd voice-to-text-app

Step 2: Create a Route and Controller for Voice-to-Text

php artisan make:controller VoiceToTextController

In routes/web.php, define a route that points to the VoiceToTextController:

Route::get('/voice-to-text', 'VoiceToTextController@index');

Step 3: Create a View for Voice-to-Text

Create a Blade view named voice_to_text.blade.php inside the resources/views directory:

<!-- resources/views/voice_to_text.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Voice to Text</title>
</head>
<body>
    <h1>Voice to Text Conversion</h1>
    <textarea id="speechInput" rows="4" cols="50"></textarea>
    <button id="startButton">Start Recording</button>

    <script>
        // Your JavaScript code for voice recognition
    </script>
</body>
</html>

Step 4: Implement JavaScript for Voice Recognition

Add the JavaScript code to capture the user’s speech using the Web Speech API and display it in the textarea:

<!-- resources/views/voice_to_text.blade.php -->
<script>
    const recognition = new webkitSpeechRecognition(); // For Chrome, use SpeechRecognition() for other browsers
    recognition.lang = 'en-US'; // Set the language code appropriately

    recognition.onresult = function(event) {
        const text = event.results[0][0].transcript;
        document.getElementById('speechInput').value = text;
    };

    document.getElementById('startButton').addEventListener('click', function() {
        recognition.start();
    });
</script>

Step 5: Send Speech Data to Laravel Backend

When the user has finished speaking, we can send the recognized text data to the Laravel backend using an AJAX request. For this, we’ll use jQuery to simplify the process:

First, include jQuery in your Blade view by adding the following line before the closing </body> tag:

<!-- resources/views/voice_to_text.blade.php -->
<!-- ... Existing content ... -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>

Now, modify the JavaScript code to send the data to the backend:

<!-- resources/views/voice_to_text.blade.php -->
<script>
    const recognition = new webkitSpeechRecognition(); // For Chrome, use SpeechRecognition() for other browsers
    recognition.lang = 'en-US'; // Set the language code appropriately

    recognition.onresult = function(event) {
        const text = event.results[0][0].transcript;
        document.getElementById('speechInput').value = text;

        // Send the recognized text to the Laravel backend using AJAX
        $.ajax({
            url: '{{ route("transcribe") }}', // Route pointing to the controller method
            method: 'POST',
            data: {
                text: text,
                _token: '{{ csrf_token() }}' // Required for CSRF protection in Laravel
            },
            success: function(response) {
                // Handle the response from the backend if needed
                console.log('Transcription saved successfully!');
            },
            error: function(xhr) {
                // Handle errors, if any
                console.error(xhr.responseText);
            }
        });
    };

    document.getElementById('startButton').addEventListener('click', function() {
        recognition.start();
    });
</script>

Step 6: Process the Recognized Text in Laravel Backend

In the VoiceToTextController, add the necessary methods for handling the transcription:

// app/Http/Controllers/VoiceToTextController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class VoiceToTextController extends Controller
{
    public function index()
    {
        return view('voice_to_text');
    }

    public function transcribe(Request $request)
    {
        // Get the recognized text from the AJAX request
        $transcription = $request->input('text');

        // Perform any processing or save the transcription to the database if needed

        // Return a response if necessary
        return response()->json(['message' => 'Transcription saved successfully!']);
    }
}

Step 7: Display Transcription Result

You can modify the JavaScript code in the view to display the transcription result received from the backend:

<!-- resources/views/voice_to_text.blade.php -->
<script>
    // ... Existing JavaScript code ...

    recognition.onresult = function(event) {
        const text = event.results[0][0].transcript;
        document.getElementById('speechInput').value = text;

        // Send the recognized text to the Laravel backend using AJAX
        // ... Existing AJAX code ...

        $.ajax({
            url: '{{ route("transcribe") }}', // Route pointing to the controller method
            method: 'POST',
            data: {
                text: text,
                _token: '{{ csrf_token() }}' // Required for CSRF protection in Laravel
            },
            success: function(response) {
                // Handle the response from the backend if needed
                console.log('Transcription saved successfully!');
                // Display the transcription result
                alert('Transcription Result: ' + response.transcription);
            },
            error: function(xhr) {
                // Handle errors, if any
                console.error(xhr.responseText);
            }
        });
    };

    // ... Rest of the JavaScript code ...
</script>

That’s it! Now you have a basic implementation of voice-to-text functionality in your Laravel application using the Web Speech API. When the user clicks the “Start Recording” button and speaks into the microphone, the recognized text will be displayed in the textarea, and the transcription will be sent to the Laravel backend for further processing or storage.

Check more

1 thought on “Step-by-Step Guide: Implementing Voice-to-Text Functionality in a Laravel Application using Web Speech API

Comments are closed.