how to play wav file in python?
You can use PyAudio. An example here on my Linux it works:
#!usr/bin/env python
#coding=utf-8
import pyaudio
import wave
#define stream chunk
chunk = 1024
#open a wav format music
f = wave.open(r"/usr/share/sounds/alsa/Rear_Center.wav","rb")
#instantiate PyAudio
p = pyaudio.PyAudio()
#open stream
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
#read data
data = f.readframes(chunk)
#play stream
while data:
stream.write(data)
data = f.readframes(chunk)
#stop stream
stream.stop_stream()
stream.close()
#close PyAudio
p.terminate()
How to play Wav sound samples from memory
You should clearly separate those two concerns:
Reading/writing WAV files (or other audio files)
Playing/recording sounds
There are several questions and answers to both topics here on SO.
This is my personal (and of course biased) recommendation:
You should use NumPy to manipulate sounds, it's much easier than handling plain Python buffers.
If for some reason you cannot use NumPy, you can still do all this, but it will be a bit more work.
For reading/writing sound files, I recommend the soundfile module (full disclosure: I'm a co-author).
For playing/recording sounds, I recommend the sounddevice module (full disclosure: I'm its main author).
When using those modules, your example would probably become something like this:
import soundfile as sf
import sounddevice as sd
samples, samplerate = sf.read('file.wav')
sd.play(samples, samplerate)
sd.wait()
changed_samples = make_change_to(samples)
sd.play(changed_samples, samplerate)
sd.wait()
If you work in an interactive Python prompt, you probably don't need the sd.wait()
calls, you can just wait until the playback has finished. Or, if you get bored of listening to it, you can use:
sd.stop()
If you know that you will use the same sampling rate for some time, you can set it as default:
sd.default.samplerate = 48000
After that, you can drop the samplerate
argument when using play()
:
sd.play(samples)
If you want to store the changed sound to a file, you can use something like this:
sf.write('changed_file.wav', changed_samples, samplerate)
Further reading:
- different options for reading/writing audio files
- different options for playback/recording
- a very basic tutorial about handling audio signals
Opening wav from URL in Python
You can also get the content of website, store it in a variable, and play it. There is no need to store it on the disk for a short file like this. Here is an example of how to do this:
import logging
import requests
import simpleaudio
sample_rate = 8000
num_channels = 2
bytes_per_sample = 2
total = sample_rate * num_channels * bytes_per_sample
logging.basicConfig(level=logging.INFO)
audio_url = "https://file-examples-com.github.io/uploads/2017/11/file_example_WAV_1MG.wav"
logging.info(f"Downloading audio file from: {audio_url}")
content = requests.get(audio_url).content
# Just to ensure that the file does not have extra bytes
blocks = len(content) // total
content = content[:total * blocks]
wave = simpleaudio.WaveObject(audio_data=content,
sample_rate=sample_rate,
num_channels=num_channels,
bytes_per_sample=bytes_per_sample)
control = wave.play()
control.wait_done()
How can I play a .wav file in python 3.6?
This:
with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
is a relative path to where your prog runs.
Use
with open('C:/Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
^^^^
Play wav file python 3
I fixed the problem by using the module pyaudio, and the module wave to read the file.
I will type example code to play a simple wave file.
import wave, sys, pyaudio
wf = wave.open('Sound1.wav')
p = pyaudio.PyAudio()
chunk = 1024
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
data = wf.readframes(chunk)
while data != '':
stream.write(data)
data = wf.readframes(chunk)
Reading *.wav files in Python
Per the documentation, scipy.io.wavfile.read(somefile)
returns a tuple of two items: the first is the sampling rate in samples per second, the second is a numpy
array with all the data read from the file:
from scipy.io import wavfile
samplerate, data = wavfile.read('./output/audio.wav')
Having issues playing a .wav file on Raspberry Pi (Python & Socket)
I eventually ended up using the PyGame module to play the audio. Here is the code:
def playSound(filename):
pygame.mixer.music.load(filename)
pygame.mixer.music.play()
def audio_player():
pygame.init()
playSound('voice.wav')
while pygame.mixer.music.get_busy() == True:
continue
return
Related Topics
Text Progress Bar in Terminal With Block Characters
What Is an Alternative to Execfile in Python 3
How to Convert an Integer to a String in Any Base
Why Are Python'S 'Private' Methods Not Actually Private
How to Sort a List of Strings Numerically
Lambda in For Loop Only Takes Last Value
How to Get Indices of N Maximum Values in a Numpy Array
Create List of Single Item Repeated N Times
About the Changing Id of an Immutable String
Is Floating Point Arbitrary Precision Available
How to Initialize a Dictionary of Distinct Empty Lists in Python
Determine the Type of an Object
Get Unique Values from a List in Python