在python上播放mp3歌曲
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20021457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Playing mp3 song on python
提问by The Mr. Totardo
I want to play my song (mp3) from python, can you give me a simplest command to do that?
我想从 python 播放我的歌曲 (mp3),你能给我一个最简单的命令吗?
This is not correct:
这是不正确的:
import wave
w = wave.open("e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3","r")
采纳答案by shad0w_wa1k3r
Try this. It's simplistic, but probably not the best method.
尝试这个。这很简单,但可能不是最好的方法。
from pygame import mixer # Load the popular external library
mixer.init()
mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3')
mixer.music.play()
Please note that pygame's support for MP3is limited. Also, as pointed out by Samy Bencherif, there won't be any silly pygame window popup when you run the above code.
请注意,pygame中的支持MP3是有限的。此外,正如Samy Bencherif所指出的,当您运行上述代码时,不会弹出任何愚蠢的 pygame 窗口。
安装很简单——
pip install pygame
回答by David
You are trying to play a .mp3as if it were a .wav.
您正在尝试将 a.mp3当作.wav.
You could try using pydubto convert it to .wavformat, and then feed that into pyAudio.
您可以尝试使用pydub将其转换为.wav格式,然后将其输入 pyAudio。
Example:
例子:
from pydub import AudioSegment
song = AudioSegment.from_mp3("original.mp3")
song.export("final.wav", format="wav")
Alternatively, use pygame, as mentioned in the other answer.
或者,使用pygame,如另一个答案中所述。
回答by hsyn
from win32com.client import Dispatch
wmp = Dispatch('WMPlayer.OCX')
liste = [r"F:\Mp3\rep.Evinden Uzakta.mp3",
r"F:\Mp3\rep___SAGOPA_KAJMER___BIR__I.MP3",
r"F:\Mp3\rep.Terzi.mp3",
r"F:\Mp3\rep. Rüya.mp3",
r"F:\Mp3\rep.Battle Edebiyat?.mp3",
r"F:\Mp3\rep_AUDIOTRACK_09.MP3",
r"F:\Mp3\rep. Sagopa Kajmer - Uzun Yollara Devam.mp3",
r"F:\Mp3\repPac_-_CHANGE.mp3",
r"F:\Mp3\rep. Herkes.mp3",
r"F:\Mp3\rep. Sagopa Kajmer - Istakoz.mp3"]
for x in liste:
mp3 = wmp.newMedia(x)
wmp.currentPlaylist.appendItem(mp3)
wmp.controls.play()
回答by Ben
Grab the VLC Python module, vlc.py, which provides full support for libVLC and pop that in site-packages. Then:
获取VLC Python 模块vlc.py,它提供对 libVLC 的完全支持并将其弹出到站点包中。然后:
>>> import vlc
>>> p = vlc.MediaPlayer("file:///path/to/track.mp3")
>>> p.play()
And you can stop it with:
你可以停止它:
>>> p.stop()
That module offers plenty beyond that (like pretty much anything the VLC media player can do), but that's the simplest and most effective means of playing one MP3.
该模块提供了更多功能(几乎就像 VLC 媒体播放器可以做的任何事情一样),但这是播放 MP3 的最简单和最有效的方法。
You could play with os.path a bit to get it to find the path to the MP3 for you, given the filename and possibly limiting the search directories.
给定文件名并可能限制搜索目录,您可以稍微使用 os.path 让它为您找到 MP3 的路径。
Full documentation and pre-prepared modules are available here. Current versions are Python 3 compatible.
完整文档和预先准备好的模块可在此处获得。当前版本与 Python 3 兼容。
回答by Michael
As it wasn't already suggested here, but is probably one of the easiest solutions:
因为这里还没有建议,但可能是最简单的解决方案之一:
import subprocess
def play_mp3(path):
subprocess.Popen(['mpg123', '-q', path]).wait()
It depends on any mpg123 compliant player, which you get e.g. for Debian using:
这取决于任何兼容 mpg123 的播放器,例如 Debian 使用的播放器:
apt-get install mpg123
or
或者
apt-get install mpg321
回答by toufikovich
A simple solution:
一个简单的解决方案:
import webbrowser
webbrowser.open("C:\Users\Public\Music\Sample Music\Kalimba.mp3")
cheers...
干杯...
回答by Tony
回答by mdeff
If you're working in the Jupyter (formerly IPython) notebook, you can
如果您在 Jupyter(以前称为 IPython)笔记本中工作,您可以
import IPython.display as ipd
ipd.Audio(filename='path/to/file.mp3')
回答by The Unnamed Engineer
Another quick and simple option...
另一个快速而简单的选择...
import os
os.system('start path/to/player/executable path/to/file.mp3')
Now you might need to make some slight changes to make it work. For example, if the player needs extra arguments or you don't need to specify the full path. But this is a simple way of doing it.
现在您可能需要进行一些细微的更改才能使其正常工作。例如,如果播放器需要额外的参数或者您不需要指定完整路径。但这是一种简单的方法。
回答by dentex
At this point, why not mentioning python-audio-tools:
在这一点上,为什么不提python-audio-tools:
- GitHub: https://github.com/tuffy/python-audio-tools
- docs: http://audiotools.sourceforge.net/programming/audiotools.html?highlight=seek#module-audiotools
- GitHub: https://github.com/tuffy/python-audio-tools
- 文档:http: //audiotools.sourceforge.net/programming/audiotools.html?highlight= seek#module- audiotools
It's the best solution I found.
这是我找到的最好的解决方案。
(I needed to install libasound2-dev, on Raspbian)
(我需要libasound2-dev在 Raspbian上安装)
Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay
代码摘录松散基于:https:
//github.com/tuffy/python-audio-tools/blob/master/trackplay
#!/usr/bin/python
import os
import re
import audiotools.player
START = 0
INDEX = 0
PATH = '/path/to/your/mp3/folder'
class TracklistPlayer:
def __init__(self,
tr_list,
audio_output=audiotools.player.open_output('ALSA'),
replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
skip=False):
if skip:
return
self.track_index = INDEX + START - 1
if self.track_index < -1:
print('--> [track index was negative]')
self.track_index = self.track_index + len(tr_list)
self.track_list = tr_list
self.player = audiotools.player.Player(
audio_output,
replay_gain,
self.play_track)
self.play_track(True, False)
def play_track(self, forward=True, not_1st_track=True):
try:
if forward:
self.track_index += 1
else:
self.track_index -= 1
current_track = self.track_list[self.track_index]
audio_file = audiotools.open(current_track)
self.player.open(audio_file)
self.player.play()
print('--> index: ' + str(self.track_index))
print('--> PLAYING: ' + audio_file.filename)
if not_1st_track:
pass # here I needed to do something :)
if forward:
pass # ... and also here
except IndexError:
print('\n--> playing finished\n')
def toggle_play_pause(self):
self.player.toggle_play_pause()
def stop(self):
self.player.stop()
def close(self):
self.player.stop()
self.player.close()
def natural_key(el):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]
def natural_cmp(a, b):
return cmp(natural_key(a), natural_key(b))
if __name__ == "__main__":
print('--> path: ' + PATH)
# remove hidden files (i.e. ".thumb")
raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))
# mp3 and wav files only list
file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)
# natural order sorting
file_list.sort(key=natural_key, reverse=False)
track_list = []
for f in file_list:
track_list.append(os.path.join(PATH, f))
TracklistPlayer(track_list)

