如何直接从内存中播放 WAV 数据? [英] How to play WAV data right from memory?

查看:30
本文介绍了如何直接从内存中播放 WAV 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在进行一项声音实验,但遇到了一个问题.我将一组波形数据保存到一个 .wav 文件并播放它,但是有没有办法跳过这一步并直接从内存中播放声音?我正在寻找一种可以跨平台工作的解决方案.

解决方案

我想你正在使用 wave 库,对吧?

文档说:

<块引用>

wave.open(file[, mode])

如果 file 是字符串,则按该名称打开文件,否则将其视为可查找的类文件对象.

这意味着您应该能够按照以下方式做一些事情:

<预><代码>>>>进口浪潮>>>从 StringIO 导入 StringIO>>>file_on_disk = open('myfile.wav', 'rb')>>>file_in_memory = StringIO(file_on_disk.read())>>>file_on_disk.seek(0)>>>file_in_memory.seek(0)>>>file_on_disk.read() == file_in_memory.read()真的>>>wave.open(file_in_memory, 'rb')<wave.Wave_read 实例在 0x1d6ab00>


编辑(见评论):以防万一您的问题不仅是从内存中读取文件,而且是从 python 中播放它...

一个选项是你使用 pymedia

导入时间、波形、pymedia.audio.sound 为声音f= wave.open( 'YOUR FILE NAME', 'rb' ) # ← 你可以在这里使用StrinIO!采样率= f.getframerate()频道= f.getnchannels()格式= sound.AFMT_S16_LEsnd= sound.Output(sampleRate, channels, format )s= f.readframes( 300000 )snd.play(s)而 snd.isPlaying(): time.sleep( 0.05 )

[来源:pymedia 教程(为简洁起见,我省略了他们的解释性评论]>

I'm currently working on a sound experiment, and I've come across one issue. I save an array of wave data to a .wav file and play it, but is there a way to skip this step and simply play the sound right from memory? I'm looking for a solution that will work cross-platform.

解决方案

I suppose you are using the wave library, right?

The docs say:

wave.open(file[, mode])

If file is a string, open the file by that name, otherwise treat it as a seekable file-like object.

This means that you should be able to do something along the lines of:

>>> import wave
>>> from StringIO import StringIO
>>> file_on_disk = open('myfile.wav', 'rb')
>>> file_in_memory = StringIO(file_on_disk.read())
>>> file_on_disk.seek(0)
>>> file_in_memory.seek(0)
>>> file_on_disk.read() == file_in_memory.read()
True
>>> wave.open(file_in_memory, 'rb')
<wave.Wave_read instance at 0x1d6ab00>


EDIT (see comments): Just in case your issue is not only about reading a file from memory but playing it from python altogether...

An option is tu use pymedia

import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' ) # ← you can use StrinIO here!
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )
while snd.isPlaying(): time.sleep( 0.05 )

[source: the pymedia tutorial (for brevity I omitted their explanatory comments]

这篇关于如何直接从内存中播放 WAV 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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