Playing MP3s in Python - Automatically handling varied sampling frequencies
<p>I am writing a python program to practice and test my Mandarin oral comprehension.  It selects a random mp3 from my designated directory and plays it (then does more stuff after).  I am using pygame to play these mp3s, but my problem is my current setup requires explicit declaration of the sampling frequency of the mp3 in order for it to play properly.  But, I have a mixture of 48 kHz and 44.1 kHz mp3s, and would like to be able to play them without distorting the sound.</p>

<pre><code>import pygame
import random
import os

filenames = [x[:-4] for x in os.listdir(filepath) if x.endswith(suffix)]

pygame.mixer.init(48000, -16, 2, 4096)
selected_filename = random.choice(filenames)
selected_filename_full = filepath + selected_filename + suffix 
pygame.mixer.music.load(selected_filename_full)
pygame.mixer.music.set_volume(volume)
pygame.mixer.music.play()
</code></pre>

<p>Is there a way to detect the sampling frequency of an mp3? Or somehow play an mp3 properly some other way?  It seems like a weird issue, whenever I double click an mp3, my music player will always play it properly, so what can I do to get the same behavior in my python code?</p>

<p>You can use <a href="http://eyed3.nicfit.net/" rel="nofollow">eyeD3</a>:</p>

<pre><code>import eyed3
e = eyed3.load(filename)
print e.info.sample_freq
</code></pre>

python pygame mp3 frequency sampling