播放从 url 检索到的声音内容? [英] Play the contents of a sound retrieved from an url?

查看:90
本文介绍了播放从 url 检索到的声音内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从以下位置检索声音:

I am retrieving the sound from:

http://translate.google.com/translate_tts

并将其写入 WAV 文件,当我双击该文件时声音播放正常,但是当我使用 python 中的 WAVE 模块打开它时,它给了我这个错误:

and writing it to a WAV file, when i double-click the file the sound plays ok, but when i use the WAVE module from python to open it, it gives me this error:

wave.Error: 文件不是以 RIFF id 开头

wave.Error: file does not start with RIFF id

我想知道有没有办法打开这个文件,或者之前不写就可以播放声音.

I want to know if there is a way for openning this file, or if it is possible to play the sound without writing it before.

相关代码如下:

url = "http://translate.google.com/translate_tts?tl=%s&q=%s" % (lang, text)
hrs = {"User-Agent":
       "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7"}

request = urllib.request.Request(url, headers = hrs)
page = urllib.request.urlopen(request)

fname = "Play"+str(int(time.time()))+".wav"
file = open(fname, 'wb')
file.write(page.read())
file.close()

读取这个文件的代码是:

And the code that reads this file is:

INPUT_FRAMES_PER_BLOCK = 1024

wf = wave.open(fname, 'r')

pa = pyaudio.PyAudio()

stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                 channels=wf.getnchannels(),
                 rate=wf.getframerate(),
                 output=True)

data = wf.readframes(INPUT_FRAMES_PER_BLOCK)

while data != '':
    stream.write(data)
    data = wf.readframes(INPUT_FRAMES_PER_BLOCK)

stream.stop_stream()
stream.close()

pa.terminate()

提前致谢!我正在使用 Python 3 顺便说一句.

Thanks in advance! I am using Python 3 BTW.

推荐答案

出现此错误是因为您正在尝试播放不是 WAV 的文件.

You have this error because you're trying to play a file that isn't a WAV.

Google 翻译生成的声音被编码为 MP3.

The sound generated by Google Translate is encoded as an MP3.

至于如何使用 Python 播放 MP3 声音,我建议您阅读 这个 StackOverflow 问题.

As for how to play an MP3 sound with Python, I'd recommend you read this StackOverflow question.

(基本上你必须安装一些库,比如 Pyglet)

(Basically you have to install some library like Pyglet)

这篇关于播放从 url 检索到的声音内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆