import pyaudio
import wave
chunk = 1024
wf = wave.open('yes.mp3', 'rb')
p = pyaudio.PyAudio()
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)
stream.close()
p.terminate()
No matter how I put this, while trying multiple methods I seem to keep getting the following error in terminal:
raise Error, 'file does not start with RIFF id'
I would use pyglet but media and all other modules aren't detected even though I'm able to import pyglet.
Any help?
You're using wave to attempt to open a file that is not wav. Instead, you're attempting to open an mp3 file. The wave module can only open wav files, so you need to convert the mp3 to wav. Here's how you can use pyglet to play an mp3 file:
import pyglet
music = pyglet.resource.media('music.mp3')
music.play()
pyglet.app.run()
It would be much simpler than the method you're trying. What errors are you getting with pyglet?
Related
I've looked all over, but anything related to this question uses audio libraries. How do I connect python to my microphone?
If you would like to record your voice using your microphone that is connected to your computer, you can try the code below:
As mentioned in this article playing-and-recording-sound-python
Pyaudio provides bindings for PortAudio, the cross-platform audio I/O library. This means that you can use pyaudio to play and record audio on a variety of platforms, including Windows, Linux, and Mac. With pyaudio, playing audio is done by writing to a Stream:
import pyaudio
import wave
chunk = 1024 # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16 # 16 bits per sample
channels = 2
fs = 44100 # Record at 44100 samples per second
seconds = 3
filename = "output.wav"
p = pyaudio.PyAudio() # Create an interface to PortAudio
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = [] # Initialize array to store frames
# Store data in chunks for 3 seconds
for i in range(0, int(fs / chunk * seconds)):
data = stream.read(chunk)
frames.append(data)
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()
print('Finished recording')
# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
i am decoding a wav file and trying to convert it to pcm_s16le to i used audioop.adpcm2lin() function but it causes sound loss for some wave files how to fix it ?
import audioop
import struct
import wave
with open(f"game_music.wav","rb") as wb:
types = struct.unpack("4s",wb.read(4))[0]
print(types)
temp = wb.read(2)
temp = wb.read(2)
channels = struct.unpack("H",wb.read(2))[0]
print(channels)
temp = wb.read(2)
sample_rate = struct.unpack("H",wb.read(2))[0]
print(sample_rate)
num_samples = struct.unpack("I",wb.read(4))[0]
print(num_samples)
audio_data = audioop.adpcm2lin(wb.read(),2,None)[0]
with wave.open(f"game_musics.wav", "w") as wav:
wav.setnchannels(channels)
wav.setsampwidth(2)
wav.setframerate(sample_rate)
wav.writeframesraw(audio_data)
for example this file working fine .
https://drive.google.com/file/d/1XAlZZ6bkSRDsnsch6fL2u708xB7xscTa/view?usp=sharing
but this file corrupts .
https://drive.google.com/file/d/1IC8p1TIyEaIi5mwMTWvflCUIhaBaR1BR/view?usp=sharing
if anyone trying to fix then you can use this to test.
its orginal version of corrupted file.
https://drive.google.com/file/d/1OyuwxMSYxiyh1rMFDJ1_k0bRp_hx5CpX/viewusp=sharing
Thanks for helping
I'm trying to process url audio streams from list of urls. Each url can have different format and I'm trying to find a library that can handle all the format kinds and give me the raw stream data that I can then process.
I have a code that can process wav stream. the problem is that some urls are in aac or mp3 formats and I need to handle each one of them correctly.
This is the code to process wav stream:
from urllib2 import urlopen
#to python3.x
#from urllib.request import urlopen
import pyaudio
pyaud = pyaudio.PyAudio()
srate=44100
stream = pyaud.open(format = pyaud.get_format_from_width(1),
channels = 1,
rate = srate,
output = True)
url = "http://myurl/hara.wav"
u = urlopen(url)
data = u.read(8192)
while data:
stream.write(data)
data = u.read(8192)
This code currently fails when the format is not wav. I tried reading about ffmpeg or vlc to format the urls but I haven't found a working way.
Any help would be appreciated. :)
I'm trying to write a python script that will play mp3 from Soundcloud URL
This is what I've already done:
from urllib.request import urlopen
url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)
data = u.read(1024)
while data:
player.play(data)
data = u.read(1024)
I tried pyaudio with many options like changing formats, channels, rate.
and I just get strange sound from the speakers, I searched Google for pyaudio playing mp3 and didn't found any information.
I tried pygame by creating Sound object by passing the bytes from the mp3 and then just by executing the play function. I am not getting any errors: the script runs but nothing is playing.
I'm working with Python 3 and Ubuntu.
If you happen to have VLC installed (or are willing to install it), then this should work:
import vlc
p = vlc.MediaPlayer("http://your_mp3_url")
p.play()
This has the advantage that it works with everything VLC works with, not just MP3. It can also be paused if you want to.
You can install vlc for python using
pip install python-vlc
Check if you can download file manually using that URL. If its protected site with username/passwd, you may need to take care of that first.
If not, here is a working code that downloads file from url using urllib2 and then plays it using pydub.
Its a two step process where first mp3 file is downloaded and saved to file and then played using external player.
import urllib2
from pydub import AudioSegment
from pydub.playback import play
mp3file = urllib2.urlopen("http://www.bensound.org/bensound-music/bensound-dubstep.mp3")
with open('./test.mp3','wb') as output:
output.write(mp3file.read())
song = AudioSegment.from_mp3("./test.mp3")
play(song)
** Update **
You did mention that you need streaming from web. In that case you may want to look at GStreamer with Python Bindings
Here is a SO link for that.
Sorry but I do not have Python3 to test here, to stream mp3 using pyaudio you will need decode it in PCM data, I know that pymedia can do it, but it is too old and just support python27.
To do this the right way you will need to know some attributes of your audio, things like samplerate, number of channels, bit resolution, to set it in the pyaudio.
I can show how I do it using python27 + pyaudio, first I will show how it is done to stream .wav
from urllib2 import urlopen
#to python3.x
#from urllib.request import urlopen
import pyaudio
pyaud = pyaudio.PyAudio()
srate=44100
stream = pyaud.open(format = pyaud.get_format_from_width(1),
channels = 1,
rate = srate,
output = True)
url = "http://download.wavetlan.com/SVV/Media/HTTP/WAV/NeroSoundTrax/NeroSoundTrax_test4_PCM_Mono_VBR_8SS_44100Hz.wav"
u = urlopen(url)
data = u.read(8192)
while data:
stream.write(data)
data = u.read(8192)
choose large buffer, python is slow in while loop, i did it using chunks of size 8192, note that format, channels and rate are the rigth attributes for this wav file, so for .wav we not need decode, it is a PCM data, now for mp3 we will need decode and put in PCM format to stream.
Lets try using pymedia
from urllib2 import urlopen
import pyaudio
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
dm= muxer.Demuxer( 'mp3' )
pyaud = pyaudio.PyAudio()
srate=44100
stream = pyaud.open(format = pyaud.get_format_from_width(2),
channels = 1,
rate = srate,
output = True)
url = "http://www.bensound.org/bensound-music/bensound-dubstep.mp3"
u = urlopen(url)
data = u.read(8192)
while data:
#Start Decode using pymedia
dec= None
s= " "
sinal=[]
while len( s ):
s= data
if len( s ):
frames= dm.parse( s )
for fr in frames:
if dec== None:
# Open decoder
dec= acodec.Decoder( dm.streams[ 0 ] )
r= dec.decode( fr[ 1 ] )
if r and r.data:
din = r.data;
s=""
#decode ended
stream.write(din)
data = u.read(8192)
This may be secret, because I never saw anyone showing how this can be done in python, for python3 I not know anything that can decode .mp3 into pieces like pymedia do.
Here these two codes are streming and working for .wav and .mp3
I am retrieving the sound from:
http://translate.google.com/translate_tts
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: 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.
Here is the relevant code:
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()
Thanks in advance!
I am using Python 3 BTW.
You have this error because you're trying to play a file that isn't a WAV.
The sound generated by Google Translate is encoded as an MP3.
As for how to play an MP3 sound with Python, I'd recommend you read this StackOverflow question.
(Basically you have to install some library like Pyglet)
Alternatively, if you want a wav file, you could install something to convert it to a wav file. Pymedia is a good module for that. The pymedia version made for current versions of python could be difficult to find, however, I have found a good place to get it at: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymedia
Here is a function that will convert the mp3 file to a wav file, and save a wav file in your file system:
def dumpWAV( name ):
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
import time, wave, string, os
name1= str.split( name, '.' )
name2= string.join( name1[ : len( name1 )- 1 ] )
# Open demuxer first
dm= muxer.Demuxer( name1[ -1 ].lower() )
dec= None
f= open( name, 'rb' )
snd= None
s= " "
while len( s ):
s= f.read( 20000 )
if len( s ):
frames= dm.parse( s )
for fr in frames:
if dec== None:
# Open decoder
dec= acodec.Decoder( dm.streams[ 0 ] )
r= dec.decode( fr[ 1 ] )
if r and r.data:
if snd== None:
snd= wave.open( name2+ '.wav', 'wb' )
snd.setparams( (r.channels, 2, r.sample_rate, 0, 'NONE','') )
snd.writeframes( r.data )
You may want to just play the mp3, but it is significantly easier to play a wav file in python. For example, pygame's support of mp3 files is limited, but it can always play a wav file.