How to play WAV data directly from memory?

I am currently working on a sound experiment, and I ran into one problem. I save the wave data array in a WAV file and play it, but is there any way to skip this step and just play the sound directly from the memory? I am looking for a solution that will work at a cross-platform level.

+4
source share
2 answers

I suppose you use a wave library , right?

The docs say:

wave.open (file [, mode])

If the file is a string, open the file with this name, otherwise treat it as a file matched for search.

This means that you must do something in accordance with:

>>> 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 problem is not only with reading a file from memory, but also with playing it from python in general ...

Tu option uses 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: pymedia tutorial (for brevity, I skipped their explanatory comments]

+1
source

Creating a wav file with generated samples of a sine wave in memory and playback in Windows:

 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() 
0
source

Source: https://habr.com/ru/post/1382054/


All Articles