如何从内存中播放WAV数据?

时间:2011-11-19 16:42:28

标签: python wav

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

2 个答案:

答案 0 :(得分:3)

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

文档说:

  

wave.open(文件[,模式])

     

如果file是字符串,请按该名称打开文件,否则将其视为可搜索文件对象。

这意味着您应该能够按照以下方式执行某些操作:

>>> 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>

编辑(参见评论):以防你的问题不只是从内存中读取文件而是从python中播放文件......

选项是使用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 )

[来源:pymedia tutorial(为简洁起见,我省略了他们的解释性说明)

答案 1 :(得分:1)

在内存中创建包含生成的正弦波样本并在Windows上播放的wav文件:

import math
import struct
import wave
import winsound
import cStringIO as StringIO

num_channels = 2
num_bytes_per_sample = 2
sample_rate_hz = 44100
sound_length_sec = 2.0
sound_freq_hz = 500

memory_file = StringIO.StringIO()
wave_file = wave.open(memory_file, 'w')
wave_file.setparams((num_channels, num_bytes_per_sample, sample_rate_hz, 0, 'NONE', 'not compressed'))

num_samples_per_channel = int(sample_rate_hz * sound_length_sec)

freq_pos = 0.0
freq_step = 2 * math.pi * sound_freq_hz / sample_rate_hz

sample_list = []
for i in range(num_samples_per_channel):
  sample = math.sin(freq_pos) * 32767
  sample_packed = struct.pack('h', sample)
  for j in range(num_channels):
    sample_list.append(sample_packed)
  freq_pos += freq_step

sample_str = ''.join(sample_list)
wave_file.writeframes(sample_str)

wave_file.close()

winsound.PlaySound(memory_file.getvalue(), winsound.SND_MEMORY)

memory_file.close()