别着急,先看示範
記得三連加關,我太慘了,都沒多少人關注我,嗚嗚!(水印名就是我b站使用者名)
前言一定要看,很重要!!!
為了讓大家真正學會,我用分子產品步驟的方式講解,這樣也能讓大家不僅在娛樂的同時,還能學到知識。東西有點多,你大可不必着急複制粘貼,你隻需要看看我的講解即可,當然,如果你能按照我的步驟親自執行每一部分代碼,那樣你會更加學到知識,最下面可以直接下載下傳完整的源碼檔案!!!别說你搞不出來了!!
第一步實作普通智能對話
代碼如下:
# coding=gbk
"""
作者:川川
時間:2021/8/21
"""
import requests
print('請輸入你想說的:')
while True:
a=input()
url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%a
te=requests.get(url).json()
data=te['data']['info']['text']
print(data)
對話效果(還是比較人工智能)

第二步文字轉蘿莉音
1-到百度ai開放平台,連結為:
https://ai.baidu.com/
,點選控制台,掃碼登入進去
2-申請百度語音技術api,步驟如下:
然後配置如下:
點選建立即可。
然後到管理用用去檢視:(我圈出來的後面要用)
開始撸代碼:
# coding=gbk
"""
作者:川川
時間:2021/8/22
私人交流群:970353786
"""
# pip install baidu-aip
from aip import AipSpeech
""" 你的 APPID AK SK 最好是用你的替換,不要用我的 """
APP_ID = '24734236'
API_KEY = 'KnmsgdYdL4v9enp2iuD5e6OS'
SECRET_KEY = 'HGhMchOle5sbzRdFqOoHkRu5P1jZR1NM'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis('空山新雨後,天氣晚來秋', 'zh', 1, {
'vol': 5, # 音量
'spd': 3, # 語速
'pit': 9, # 語調
'per': 3, # 0:女 1:男 3:逍遙 4:小蘿莉
})
# 識别正确傳回語音二進制 錯誤則傳回dict 參照下面錯誤碼
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as f:
f.write(result)
運作後,不出意外,你會看到生成了一個mp3音頻,你也可以手動點開播放以下看看。
第三步播放音頻
# coding=gbk
"""
作者:川川
時間:2021/8/21
"""
from playsound import playsound
playsound('auido.mp3')
from platform import system
from abc import ABC, abstractmethod
operating_system = system()
if operating_system == 'Windows':
from ctypes import c_buffer, windll
from random import random
from time import sleep
from sys import getfilesystemencoding
elif operating_system == 'Darwin':
from AppKit import NSSound
from Foundation import NSURL
from time import sleep
elif operating_system == 'Linux':
# pathname2url escapes non-URL-safe characters
import os
try:
from urllib.request import pathname2url
except ImportError:
# python 2
from urllib import pathname2url
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
class PlaysoundException(Exception):
pass
class playsoundBase(ABC):
def __init__(self):
pass
@abstractmethod
def play(self, sound, block):
raise NotImplemented
@abstractmethod
def stop(self):
raise NotImplemented
class playsoundWin(playsoundBase):
alias = ''
def winCommand(self, *command):
buf = c_buffer(255)
command = ' '.join(command).encode(getfilesystemencoding())
errorCode = int(windll.winmm.mciSendStringA(command, buf, 254, 0))
if errorCode:
errorBuffer = c_buffer(255)
windll.winmm.mciGetErrorStringA(errorCode, errorBuffer, 254)
exceptionMessage = (
'\n Error ' + str(errorCode) + ' for command:\n'
+ command.decode() + '\n ' + errorBuffer.value.decode())
raise PlaysoundException(exceptionMessage)
return buf.value
def play(self, sound, block=True):
self.alias = 'playsound_' + str(random())
self.winCommand('open "' + sound + '" alias', self.alias)
self.winCommand('set', self.alias, 'time format milliseconds')
durationInMS = self.winCommand('status', self.alias, 'length')
self.winCommand('play', self.alias, 'from 0 to', durationInMS.decode())
if block:
sleep(float(durationInMS) / 1000.0)
def stop(self):
self.winCommand('stop', self.alias)
def close(self):
self.winCommand('close', self.alias)
class playsoundOSX(playsoundBase):
def play(self, sound, block=True):
if '://' not in sound:
if not sound.startswith('/'):
from os import getcwd
sound = getcwd() + '/' + sound
sound = 'file://' + sound
url = NSURL.URLWithString_(sound)
nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)
if not nssound:
raise IOError('Unable to load sound named: ' + sound)
nssound.play()
if block:
sleep(nssound.duration())
def stop(self):
raise NotImplemented
class playsoundNix(playsoundBase):
def play(self, sound, block=True):
if not block:
raise NotImplementedError(
"block=False cannot be used on this platform yet")
Gst.init(None)
playbin = Gst.ElementFactory.make('playbin', 'playbin')
if sound.startswith(('http://', 'https://')):
playbin.props.uri = sound
else:
playbin.props.uri = 'file://' + pathname2url(
os.path.abspath(sound))
set_result = playbin.set_state(Gst.State.PLAYING)
if set_result != Gst.StateChangeReturn.ASYNC:
raise PlaysoundException(
"playbin.set_state returned " + repr(set_result))
# FIXME: use some other bus method than poll() with block=False
# https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html
bus = playbin.get_bus()
bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
playbin.set_state(Gst.State.NULL)
def stop(self):
raise NotImplemented
operating_system = 'Windows'
if operating_system == 'Windows':
playsound = playsoundWin
elif operating_system == 'Darwin':
playsound = playsoundOSX
elif operating_system == 'Linux':
playsound = playsoundNix
del operating_system
第四步綜合上述代碼
# coding=gbk
"""
作者:川川
時間:2021/8/22
私人交流群:970353786
"""
from play import playsound
from aip import AipSpeech
import requests
""" 你的 APPID AK SK 不要用我的 """
APP_ID = '24734236'
API_KEY = 'KnmsgdYdL4v9enp2iuD5e6OS'
SECRET_KEY = 'HGhMchOle5sbzRdFqOoHkRu5P1jZR1NM'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
print('請輸入你想說的:')
while True:
a=input()
url='https://api.ownthink.com/bot?appid=9ffcb5785ad9617bf4e64178ac64f7b1&spoken=%s'%a
te=requests.get(url).json()
data=te['data']['info']['text']
print(data)
result = client.synthesis(data, 'zh', 1, {
'vol': 8, # 音量
'spd': 5, # 語速
'pit': 9, # 語調
'per': 4, # 0:女 1:男 3:逍遙 4:小蘿莉
})
# 識别正确傳回語音二進制 錯誤則傳回dict 參照下面錯誤碼
if not isinstance(result, dict):
with open('auido.mp3', 'wb+') as f:
f.write(result)
p = playsound()
voice_path = r"auido.mp3"
p.play(voice_path) # 播放
p.close() # 停止
完整代碼下載下傳位址
https://github.com/89461561511656/bot
https://github.com/89461561511656/bot