在一段时间我正在研究的聊天脚本中,当收到新消息时,我使用winsound python库播放'ding'声音(ding.wav)。现在我想知道如何使用.ogg音频文件为linux工作。代码如下:
import sys
import util
import thread
import socket
import winsound
class ClientSocket():
rbufsize = -1
wbufsize = 0
def __init__(self, address, nickname=''):
if type(address) == type(()) and type(address[0]) == type('') and type(address[1]) == type(1):
pass
else:
print ('Address is of incorrect type. \n' +
'Must be (serverHost (str), serverPort (int)).')
sys.exit(1)
if nickname:
self.changeNick(nickname)
else:
self.changeNick(raw_input('Nickname: '))
self.prompt_on = False
self.address = address
def connect(self):
self.connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect(self.address)
self.rfile = self.connection.makefile('rb', self.rbufsize)
self.wfile = self.connection.makefile('wb', self.wbufsize)
self.wfile.write('/nick ' + self.nickname + '\n')
def serve_forever(self):
self.connect()
thread.start_new_thread(self.acceptinput,())
line = ""
while line not in ('/exit','/quit', '/q'):
self.prompt_on = True
line = raw_input(self.prompt)
self.prompt_on = False
if line[:2] == '/n' or line[:5] == '/nick':
self.changeNick(line.split(' ', 1)[1].strip())
self.wfile.write(line + '\n')
self.close()
self.connection.shutdown(socket.SHUT_RDWR)
self.connection.close()
def changeNick(self, newNick):
self.nickname = newNick
self.prompt = self.nickname+': '
self.backspace = '\b' * len(self.prompt)
def acceptinput(self):
while 1:
data = self.rfile.readline().strip()
if data:
self.writedata(data)
if 'Nickname successfully changed to' in data:
self.changeNick(data.split('"')[1])
def writedata(self, data):
if self.prompt_on:
output = data if len(data) >= len(self.prompt) else data + ' ' * (len(self.prompt) - len(data))
winsound.PlaySound("ding.wav", winsound.SND_FILENAME)
sys.stdout.write(self.backspace + output + '\n' + self.prompt)
sys.stdout.flush()
else:
print data
def close(self):
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
self.rfile.close()
def main():
serverHost = raw_input('Server IP/Hostname: ')
if not serverHost:
serverHost = util.getIP()
else:
serverHost = socket.gethostbyname(serverHost)
serverPort = input('Server Port: ')
address = (serverHost, serverPort)
client = ClientSocket(address)
print 'Connecting to server on %s:%s' % (serverHost, serverPort)
client.serve_forever()
if __name__ == '__main__':
main()
如果有人可以帮我转换它来播放.ogg文件,那就太棒了:))
谢谢,肖恩。
答案 0 :(得分:3)
最后,我最终使用了pygame库:
import pygame
pygame.init()
pygame.mixer.music.load("ding.ogg")
pygame.mixer.music.play()