嗨,所以我想做一个 spotify 语音助手,发现一个人的教程,他刚刚浏览了他的代码并解释了它,并在下面留下了一个 github 链接,我用它改变了设置为我工作,但我得到一个恼人的错误,我会把代码放在我有 main.py,pepper.py 和 setup.txt 的 3 个文件中
main.py:
import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth
from pepper import *
# Set variables from setup.txt
setup = pd.read_csv('C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']
# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope,
username=username)
spotify = sp.Spotify(auth_manager=auth_manager)
# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
d['name'] = d['name'].replace('’', '\'')
if d['name'] == device_name:
deviceID = d['id']
break
# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'High Definition Audio Device' # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
if microphone_name == "High Definition Audio Device":
m = Microphone(device_index=i)
while True:
with m as source:
r.adjust_for_ambient_noise(source=source)
audio = r.listen(source=source)
command = None
try:
command = r.recognize_google(audio_data=audio).lower()
except UnknownValueError:
continue
print(command)
words = command.split()
if len(words) <= 1:
print('Could not understand. Try again')
continue
name = ' '.join(words[1:])
try:
if words[0] == 'al':
uri = get_al_uri(spotify=spotify, name=name)
play_al(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'artist':
uri = get_artist_uri(spotify=spotify, name=name)
play_artist(spotify=spotify, device_id=deviceID, uri=uri)
elif words[0] == 'play':
uri = get_track_uri(spotify=spotify, name=name)
play_track(spotify=spotify, device_id=deviceID, uri=uri)
else:
print('Specify either "al", "artist" or "play". Try Again')
except InvalidSearchError:
print('InvalidSearchError. Try Again')
pepper.py:
from spotipy import Spotify
class InvalidSearchError(Exception):
pass
def get_al_uri(spotify: Spotify, name: str) -> str:
"""
:param spotify: Spotify object to make the search from
:param name: al name
:return: Spotify uri of the desired al
"""
# Replace all spaces in name with '+'
original = name
name = name.replace(' ', '+')
results = spotify.search(q=name, limit=1, type='al')
if not results['als']['items']:
raise InvalidSearchError(f'No al named "{original}"')
al_uri = results['als']['items'][0]['uri']
return al_uri
def get_artist_uri(spotify: Spotify, name: str) -> str:
"""
:param spotify: Spotify object to make the search from
:param name: al name
:return: Spotify uri of the desired artist
"""
# Replace all spaces in name with '+'
original = name
name = name.replace(' ', '+')
results = spotify.search(q=name, limit=1, type='artist')
if not results['artists']['items']:
raise InvalidSearchError(f'No artist named "{original}"')
artist_uri = results['artists']['items'][0]['uri']
print(results['artists']['items'][0]['name'])
return artist_uri
def get_track_uri(spotify: Spotify, name: str) -> str:
"""
:param spotify: Spotify object to make the search from
:param name: track name
:return: Spotify uri of the desired track
"""
# Replace all spaces in name with '+'
original = name
name = name.replace(' ', '+')
results = spotify.search(q=name, limit=1, type='track')
if not results['tracks']['items']:
raise InvalidSearchError(f'No track named "{original}"')
track_uri = results['tracks']['items'][0]['uri']
return track_uri
def play_al(spotify=None, device_id=None, uri=None):
spotify.start_playback(device_id=device_id, context_uri=uri)
def play_artist(spotify=None, device_id=None, uri=None):
spotify.start_playback(device_id=device_id, context_uri=uri)
def play_track(spotify=None, device_id=None, uri=None):
spotify.start_playback(device_id=device_id, uris=[uri])
和 setup.txt:
client_id=...
client_secret=...
device_name=Yousif
redirect_uri=s://yousifisdaddy/
username=wsk5vzl3hw3i611gxog2il
scope=user-read-private user-read-playback-state user-modify-playback-state
我确实把我的重定向 uri 那在我的 spotify 应用程序中找到,我把我的客户端 ID 和秘密 ID 和我的 setup.txt 位置,但显然不得不模糊客户端 ID 和秘密 ID
和我得到的错误是:
File "c:/Users/Yousif/Documents/Python spotify/main.py", line 9
setup = pd.read_csv('C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
改变
setup = pd.read_csv('C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
到
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
将路径标记为原始字符串将防止反斜杠转义。
这样做的原因:
Python 使用string escape sequences来支持 unicode:
从文档中:
\N{name}: Character named name in the Unicode database
\ux: Character with 16-bit hex value x
\Uxx: Character with 32-bit hex value xx
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(59条)