BeginningDeveloperFeaturedGoogle DevelopersHTML5NewbiePHPProgramming Language

Google Text to Speech API ด้วยภาษา PHP

วิธีการพัฒนาแอพพลิเคชันด้วยภาษา PHP ร่วมกับการใช้งาน API ของ Google อย่าง Google Text to Speech API ในการแปลงประโยคเป็นไฟล์ MP3 นำมาออกเสียงผ่านหน้าเว็บไซต์

banner

เป็น Tutorial สั้นๆ ที่เห็นไอเดียจากเว็บไซต์เมืองนอกหลายเว็บทำกัน ก็เลยหยิบมาลองให้ศึกษาทำตามดู

แนวทางการคิดคือ

  • GET ค่าตัวแปรผ่าน Parameter (จะเป็น POST ก็ได้นะ)
  • ทำการส่ง URL ผ่าน API ของ Google Text To Speech ของ Google Translate
  • แปลง File ที่รับค่ามาเป็น MP3 ให้สร้างไฟล์เก็บไว้บน Server ของเว็บไซต์เรา
  • หยิบ Code HTML5 มาแสดง Audio ไฟล์ของเว็บไซต์เราที่ทำการ Speech จากประโยคของเรา

ดังนั้น Code ที่ต้องทำก็คือ

<?php
	$text = substr($_GET['words'], 0, 100);
    $lang = "th";
    $file  = md5($lang."?".urlencode($text));
    $file = "audio/" . $file .".mp3";
    
    if(!is_dir("audio/"))
        mkdir("audio/");
    else
        if(substr(sprintf('%o', fileperms('audio/')), -4)!="0777")
            chmod("audio/", 0777);


    if (!file_exists($file))
    {
        $mp3 = file_get_contents(
        'http://translate.google.com/translate_tts?ie=UTF-8&q='. urlencode($text) .'&tl='. $lang .'&total=1&idx=0&textlen=5&prev=input');
        file_put_contents($file, $mp3);
    }

?>
<!DOCTYPE html>
<!--[if IE 7]>
<html class="ie ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html class="ie ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width">
<body>
<div align="center">
<audio controls="controls" autoplay="autoplay">
  <source src="<?php echo $file; ?>" type="audio/mp3" />
</audio>
</div>
<div align="center"><a href="<?php echo $file; ?>">Download File MP3 ที่ทดสอบที่นี่</a><br/>คลิกขวา เลือก Save Target As</div>
</body>
</html>

สร้าง Directory ชื่อ audio ขึ้นมาเซ็ต CHMOD ให้เป็น 0777 เพื่อเก็บไฟล์ ที่นี้ก็ลองทดลองเล่นดูเลยครับ

Screen Shot 2557-07-18 at 6.46.01 PM

ทดสอบได้ที่: https://www.daydev.com/apps/speech/index.php?words=%E0%B9%84%E0%B8%AD%E0%B9%89%E0%B8%AA%E0%B8%B2%E0%B8%94

Source Code: ให้ตายเถอะ Copy ไปก็ใช้ได้แล้ว อย่าได้ถามผมใน Facebook เลยนะครับ

 

Asst. Prof. Banyapon Poolsawas

อาจารย์ประจำสาขาวิชาการออกแบบเชิงโต้ตอบ และการพัฒนาเกม วิทยาลัยครีเอทีฟดีไซน์ & เอ็นเตอร์เทนเมนต์เทคโนโลยี มหาวิทยาลัยธุรกิจบัณฑิตย์ ผู้ก่อตั้ง บริษัท Daydev Co., Ltd, (เดย์เดฟ จำกัด)

Related Articles

Back to top button
Game & Mobile Development AR VR XR
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Adblock Detected

เราตรวจพบว่าคุณใช้ Adblock บนบราวเซอร์ของคุณ,กรุณาปิดระบบ Adblock ก่อนเข้าอ่าน Content ของเรานะครับ, ถือว่าช่วยเหลือกัน