Play audio with Python
How can I play audio (it would be like a 1 second sound) from a Python script?
It would be best if it was platform independent, but firstly it needs to work on a Mac.
I know I could just execute the afplay file.mp3
command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
python audio
add a comment |
How can I play audio (it would be like a 1 second sound) from a Python script?
It would be best if it was platform independent, but firstly it needs to work on a Mac.
I know I could just execute the afplay file.mp3
command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
python audio
add a comment |
How can I play audio (it would be like a 1 second sound) from a Python script?
It would be best if it was platform independent, but firstly it needs to work on a Mac.
I know I could just execute the afplay file.mp3
command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
python audio
How can I play audio (it would be like a 1 second sound) from a Python script?
It would be best if it was platform independent, but firstly it needs to work on a Mac.
I know I could just execute the afplay file.mp3
command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
python audio
python audio
edited Aug 27 '15 at 23:23
Chachmu
1,71642132
1,71642132
asked Nov 4 '08 at 3:11
Josh HuntJosh Hunt
4,213236792
4,213236792
add a comment |
add a comment |
22 Answers
22
active
oldest
votes
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
8
But how do I play a.wav
file?
– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
add a comment |
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I addedtime.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1
– Nagabhushan S N
Nov 22 '18 at 6:15
add a comment |
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
add a comment |
In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.
I've linked the implementation above, but a simplified version follows:
import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp
flag stops ffplay from showing a new window, and the -autoexit
flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
add a comment |
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev.
Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
add a comment |
If you need portable Python audio library try PyAudio. It certainly has a mac port.
As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some PyAudio - PyLame sample here.
add a comment |
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
$ pip install playsound
Once you've installed, you can use it like this:
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
add a comment |
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.
add a comment |
You can see this: http://www.speech.kth.se/snack/
s = Sound()
s.read('sound.wav')
s.play()
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
add a comment |
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with theplaysound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...
– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
|
show 5 more comments
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
add a comment |
Also on OSX - from SO, using OSX's afplay command:
import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
add a comment |
You can't do this without a nonstandard library.
for windows users who end up in this thread, try pythonwin. PyGame has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.
add a comment |
VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:
https://wiki.videolan.org/Python_bindings
But it does rely on the VLC application, unfortunately
add a comment |
Try PySoundCard which uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
add a comment |
Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:
# playNote.py
# Demonstrates how to play a single note.
from music import * # import music library
note = Note(C4, HN) # create a middle C half note
Play.midi(note) # and play it!
add a comment |
If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like
play "bah.wav"
It starts to play in about a half-second on my machine.
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
add a comment |
Simply You can do it with the help of cvlc-
I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
add a comment |
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay
add a comment |
This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.
import soundfile as sf
import soundcard as sc
default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')
default_speaker.play(samples, samplerate=samplerate)
See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
add a comment |
To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.
from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])
It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.
add a comment |
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f260738%2fplay-audio-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
22 Answers
22
active
oldest
votes
22 Answers
22
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
8
But how do I play a.wav
file?
– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
add a comment |
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
8
But how do I play a.wav
file?
– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
add a comment |
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
You can find information about Python audio here: http://wiki.python.org/moin/Audio/
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.
answered Nov 4 '08 at 3:27
Jeremy RutenJeremy Ruten
125k34157184
125k34157184
8
But how do I play a.wav
file?
– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
add a comment |
8
But how do I play a.wav
file?
– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
8
8
But how do I play a
.wav
file?– theonlygusti
Dec 27 '16 at 18:27
But how do I play a
.wav
file?– theonlygusti
Dec 27 '16 at 18:27
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
@theonlygusti See here, for example.
– Anderson Green
Dec 4 '17 at 19:35
add a comment |
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I addedtime.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1
– Nagabhushan S N
Nov 22 '18 at 6:15
add a comment |
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I addedtime.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1
– Nagabhushan S N
Nov 22 '18 at 6:15
add a comment |
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.
pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()
You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation
edited Sep 1 '16 at 1:00
answered Nov 4 '08 at 4:40
TMLTML
10.8k32941
10.8k32941
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I addedtime.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1
– Nagabhushan S N
Nov 22 '18 at 6:15
add a comment |
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I addedtime.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1
– Nagabhushan S N
Nov 22 '18 at 6:15
15
15
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
Please post a sample of how to do this
– Jonathan
Jul 2 '15 at 8:33
2
2
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
You have to initialize pygame mixer too. Use pygame.mixer.init() before these commands.
– aquaman
Aug 31 '16 at 10:59
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
@aquaman fair point :)
– TML
Sep 1 '16 at 1:00
For me, this was not working. I mean, it was playing but no sound. I added
time.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1– Nagabhushan S N
Nov 22 '18 at 6:15
For me, this was not working. I mean, it was playing but no sound. I added
time.sleep(5)
at the end and that worked. Python 3.6 on Windows 8.1– Nagabhushan S N
Nov 22 '18 at 6:15
add a comment |
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
add a comment |
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
add a comment |
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:
> pip install simpleaudio
Then:
import simpleaudio as sa
wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()
Make sure to use uncompressed 16 bit PCM files.
edited Mar 29 '16 at 15:21
answered Mar 29 '16 at 12:17
Erwin MayerErwin Mayer
10.6k661101
10.6k661101
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
add a comment |
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
Nice, thanks -- useful for games that need to play short sound effects, and supports Python 3.
– Thomas Perl
Dec 18 '16 at 15:31
add a comment |
In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.
I've linked the implementation above, but a simplified version follows:
import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp
flag stops ffplay from showing a new window, and the -autoexit
flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
add a comment |
In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.
I've linked the implementation above, but a simplified version follows:
import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp
flag stops ffplay from showing a new window, and the -autoexit
flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
add a comment |
In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.
I've linked the implementation above, but a simplified version follows:
import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp
flag stops ffplay from showing a new window, and the -autoexit
flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
In pydub we've recently opted to use ffplay (via subprocess) from the ffmpeg suite of tools, which internally uses SDL.
It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac.
I've linked the implementation above, but a simplified version follows:
import subprocess
def play(audio_file_path):
subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path])
The -nodisp
flag stops ffplay from showing a new window, and the -autoexit
flag causes ffplay to exit and return a status code when the audio file is done playing.
edit: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
edited Jan 7 '16 at 15:57
answered Dec 23 '13 at 15:54
JiaaroJiaaro
45.4k32135170
45.4k32135170
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
add a comment |
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
1
1
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
Pydub looks like it has quite a bit of potential as a wrapper library - I'm installing it now.
– Shadow
Jun 8 '15 at 5:49
1
1
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
Damn PyDub looks nice and it's still really active.
– corysimmons
Jan 5 '16 at 3:33
add a comment |
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev.
Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
add a comment |
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev.
Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
add a comment |
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev.
Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
Sorry for the late reply, but I think this is a good place to advertise my library ...
AFAIK, the standard library has only one module for playing audio: ossaudiodev.
Sadly, this only works on Linux and FreeBSD.
UPDATE: There is also winsound, but obviously this is also platform-specific.
For something more platform-independent, you'll need to use an external library.
My recommendation is the sounddevice module (but beware, I'm the author).
The package includes the pre-compiled PortAudio library for Mac OS X and Windows, and can be easily installed with:
pip install sounddevice --user
It can play back sound from NumPy arrays, but it can also use plain Python buffers (if NumPy is not available).
To play back a NumPy array, that's all you need (assuming that the audio data has a sampling frequency of 44100 Hz):
import sounddevice as sd
sd.play(myarray, 44100)
For more details, have a look at the documentation.
It cannot read/write sound files, you'll need a separate library for that.
edited Jan 17 '17 at 7:11
answered Dec 9 '15 at 12:37
MatthiasMatthias
2,08711832
2,08711832
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
add a comment |
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
Great! Just what I needed to make a class demo program about waves.
– Bill N
Oct 1 '18 at 20:59
add a comment |
If you need portable Python audio library try PyAudio. It certainly has a mac port.
As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some PyAudio - PyLame sample here.
add a comment |
If you need portable Python audio library try PyAudio. It certainly has a mac port.
As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some PyAudio - PyLame sample here.
add a comment |
If you need portable Python audio library try PyAudio. It certainly has a mac port.
As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some PyAudio - PyLame sample here.
If you need portable Python audio library try PyAudio. It certainly has a mac port.
As for mp3 files: it's certainly doable in "raw" Python, only I'm afraid you'd have to code everything yourself :). If you can afford some external library I've found some PyAudio - PyLame sample here.
answered Feb 3 '09 at 15:08
Grzegorz GacekGrzegorz Gacek
6912
6912
add a comment |
add a comment |
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
$ pip install playsound
Once you've installed, you can use it like this:
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
add a comment |
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
$ pip install playsound
Once you've installed, you can use it like this:
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
add a comment |
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
$ pip install playsound
Once you've installed, you can use it like this:
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
Try playsound which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
$ pip install playsound
Once you've installed, you can use it like this:
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
answered Nov 27 '17 at 13:57
yehan jayayehan jaya
6112
6112
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
add a comment |
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
9
9
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
Reading this made me so emotional. My eyes literally teared up with happiness. Did not expect that kind of reaction from myself. (They linked to a module I made.)
– ArtOfWarfare
Jan 24 '18 at 14:51
add a comment |
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.
add a comment |
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.
add a comment |
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.
Pyglet has the ability to play back audio through an external library called AVbin. Pyglet is a ctypes wrapper around native system calls on each platform it supports. Unfortunately, I don't think anything in the standard library will play audio back.
answered Nov 4 '08 at 14:37
technomalogicaltechnomalogical
2,22712038
2,22712038
add a comment |
add a comment |
You can see this: http://www.speech.kth.se/snack/
s = Sound()
s.read('sound.wav')
s.play()
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
add a comment |
You can see this: http://www.speech.kth.se/snack/
s = Sound()
s.read('sound.wav')
s.play()
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
add a comment |
You can see this: http://www.speech.kth.se/snack/
s = Sound()
s.read('sound.wav')
s.play()
You can see this: http://www.speech.kth.se/snack/
s = Sound()
s.read('sound.wav')
s.play()
edited Dec 24 '12 at 8:07
Mehul Mistri
12.7k136391
12.7k136391
answered Dec 24 '12 at 7:48
user1926182user1926182
5111
5111
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
add a comment |
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
3
3
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
Looks so clean, I wish there was a pip package for this. Ease of install is key
– Jonathan
Jul 2 '15 at 8:32
add a comment |
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with theplaysound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...
– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
|
show 5 more comments
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with theplaysound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...
– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
|
show 5 more comments
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:
from AppKit import NSSound
sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()
One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.
from time import sleep
sleep(sound.duration())
Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.
pip install playsound
Then run it like this:
from playsound import playsound
playsound('/path/to/file.wav', block = False)
MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.
edited May 23 '17 at 12:18
Community♦
11
11
answered Jan 25 '16 at 2:24
ArtOfWarfareArtOfWarfare
12.7k786136
12.7k786136
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with theplaysound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...
– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
|
show 5 more comments
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with theplaysound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...
– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
I get the following error: "Can't convert 'bytes' object to str implicitly" on Python 3.5 (Windows).
– Erwin Mayer
Mar 29 '16 at 12:24
@ErwinMayer - Are you talking about with the
playsound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...– ArtOfWarfare
Mar 29 '16 at 13:30
@ErwinMayer - Are you talking about with the
playsound
module I wrote? I haven't tested it on anything newer than Python 2.7.11... I can certainly look into fixing this on 3.5...– ArtOfWarfare
Mar 29 '16 at 13:30
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
Indeed. It must be due to Python 3 differences.
– Erwin Mayer
Mar 29 '16 at 15:20
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
AppKit is a dependency.
– Chris Larson
Dec 30 '16 at 19:08
2
2
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
@ArtOfWarfare That's simply not true. It is installed with the system python, but not with most distributions, including the official distributions from python.org. Most folks I know who use python install one of the distributions to get past the SIP restrictions. To get AppKit for most distributions, a user needs to pip install pyobjc. Which makes it most definitely a dependency.
– Chris Larson
Dec 30 '16 at 23:25
|
show 5 more comments
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
add a comment |
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
add a comment |
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.
import wave
import io
from AppKit import NSSound
wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())
wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())
seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()
wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])
wave_shell.close()
wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()
answered Jan 2 '16 at 16:53
AaronAaron
211
211
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
add a comment |
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
This is far more complicated than necessary - they asked how to simply play a sound, not how to manipulate it and then play it. My answer trims the unnecessary 90% from this answer and leaves exactly what the asker wanted - playing a sound from a file in OS X using Python. stackoverflow.com/a/34984200/901641
– ArtOfWarfare
Jan 25 '16 at 2:26
add a comment |
Also on OSX - from SO, using OSX's afplay command:
import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
add a comment |
Also on OSX - from SO, using OSX's afplay command:
import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
add a comment |
Also on OSX - from SO, using OSX's afplay command:
import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.
Also on OSX - from SO, using OSX's afplay command:
import subprocess
subprocess.call(["afplay", "path/to/audio/file"])
UPDATE: All this does is specify how to do what the OP wanted to avoid doing in the first place. I guess I posted this here because what OP wanted to avoid was the info I was looking for. Whoops.
edited Feb 16 '18 at 16:53
answered Jan 31 '15 at 5:45
MikeiLLMikeiLL
3,00112239
3,00112239
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
add a comment |
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Works great though does pause execution while it plays. Perhaps there is an async way to call this?
– Praxiteles
Feb 4 '16 at 6:49
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
Good questions @Praxiteles. Possibly with threading. see here Please report back if you have a chance to experiment with it.
– MikeiLL
Feb 5 '16 at 15:51
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP explicitly asked for alternatives to this.
– whitey04
May 19 '16 at 20:14
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
The OP is/was looking for an alternative to "execute the afplay file.mp3 command from within Python", and subprocessing still happens within Python, doesn't it. I stand corrected. But it probably doesn't hurt to have this little post here as it may help others.
– MikeiLL
May 19 '16 at 20:23
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
@whitey04 I (finally) see what you're saying.
– MikeiLL
Feb 16 '18 at 16:50
add a comment |
You can't do this without a nonstandard library.
for windows users who end up in this thread, try pythonwin. PyGame has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.
add a comment |
You can't do this without a nonstandard library.
for windows users who end up in this thread, try pythonwin. PyGame has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.
add a comment |
You can't do this without a nonstandard library.
for windows users who end up in this thread, try pythonwin. PyGame has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.
You can't do this without a nonstandard library.
for windows users who end up in this thread, try pythonwin. PyGame has some sound support. For hardware accelerated game audio, you'll probably need to call OpenAL or similar through ctypes.
answered Nov 4 '08 at 4:52
Dustin GetzDustin Getz
13.2k1068121
13.2k1068121
add a comment |
add a comment |
VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:
https://wiki.videolan.org/Python_bindings
But it does rely on the VLC application, unfortunately
add a comment |
VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:
https://wiki.videolan.org/Python_bindings
But it does rely on the VLC application, unfortunately
add a comment |
VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:
https://wiki.videolan.org/Python_bindings
But it does rely on the VLC application, unfortunately
VLC has some nice python bindings here, for me this worked better than pyglet, at least on Mac OS:
https://wiki.videolan.org/Python_bindings
But it does rely on the VLC application, unfortunately
answered May 9 '15 at 14:22
alexvicegrabalexvicegrab
384212
384212
add a comment |
add a comment |
Try PySoundCard which uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
add a comment |
Try PySoundCard which uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
add a comment |
Try PySoundCard which uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
Try PySoundCard which uses PortAudio for playback which is available on many platforms.
In addition, it recognizes "professional" sound devices with lots of channels.
Here a small example from the Readme:
from pysoundcard import Stream
"""Loop back five seconds of audio data."""
fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs*5/blocksize)):
s.write(s.read(blocksize))
s.stop()
edited Oct 19 '17 at 14:04
kenorb
68.1k29405404
68.1k29405404
answered May 28 '16 at 17:30
Stefan BalkeStefan Balke
135
135
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
add a comment |
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
Though interesting, link-only answers are discouraged. At the minimum, you should include in your answer a short example of using it. That also protects your answer from losing all its value, should the repository be renamed and the link go dangling.
– spectras
May 29 '16 at 11:04
add a comment |
Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:
# playNote.py
# Demonstrates how to play a single note.
from music import * # import music library
note = Note(C4, HN) # create a middle C half note
Play.midi(note) # and play it!
add a comment |
Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:
# playNote.py
# Demonstrates how to play a single note.
from music import * # import music library
note = Note(C4, HN) # create a middle C half note
Play.midi(note) # and play it!
add a comment |
Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:
# playNote.py
# Demonstrates how to play a single note.
from music import * # import music library
note = Note(C4, HN) # create a middle C half note
Play.midi(note) # and play it!
Pypi has a list of modules for python in music. My favorite would be jython because it has more resources and libraries for music. As example of of code to play a single note from the textbook:
# playNote.py
# Demonstrates how to play a single note.
from music import * # import music library
note = Note(C4, HN) # create a middle C half note
Play.midi(note) # and play it!
edited Feb 16 '18 at 15:13
answered Feb 16 '18 at 15:08
Kardi TeknomoKardi Teknomo
36429
36429
add a comment |
add a comment |
If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like
play "bah.wav"
It starts to play in about a half-second on my machine.
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
add a comment |
If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like
play "bah.wav"
It starts to play in about a half-second on my machine.
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
add a comment |
If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like
play "bah.wav"
It starts to play in about a half-second on my machine.
If you're on OSX, you can use the "os" module or "subprocess" etc. to call the OSX "play" command. From the OSX shell, it looks like
play "bah.wav"
It starts to play in about a half-second on my machine.
answered Mar 27 '14 at 13:33
MoondoggyMoondoggy
7615
7615
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
add a comment |
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
1
1
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
I'd be interested to see the syntax for both of these methods.
– MikeiLL
Jan 31 '15 at 5:41
add a comment |
Simply You can do it with the help of cvlc-
I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
add a comment |
Simply You can do it with the help of cvlc-
I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
add a comment |
Simply You can do it with the help of cvlc-
I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
Simply You can do it with the help of cvlc-
I did it in this way:
import os
os.popen2("cvlc /home/maulo/selfProject/task.mp3 --play-and-exit")
/home/maulo/selfProject/task.mp3. This is the location of my mp3 file.
with the help of "--play-and-exit" you will be able to play again the sound without ending the vlc process.
edited Mar 20 '16 at 15:19
ridvankucuk
1,91311635
1,91311635
answered Mar 20 '16 at 14:41
pyAddictpyAddict
43158
43158
add a comment |
add a comment |
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay
add a comment |
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay
add a comment |
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay
Put this at the top of your python script you are writing:
import subprocess
If the wav file IS in the directory of the python script:
f = './mySound.wav'
subprocess.Popen(['aplay','-q',f)
If the wav file IS NOT in the directory of the python script:
f = 'mySound.wav'
subprocess.Popen(['aplay','-q', 'wav/' + f)
If you want to learn more about aplay:
man aplay
answered Nov 11 '16 at 22:16
CrawsomeCrawsome
45113
45113
add a comment |
add a comment |
This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.
import soundfile as sf
import soundcard as sc
default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')
default_speaker.play(samples, samplerate=samplerate)
See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
add a comment |
This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.
import soundfile as sf
import soundcard as sc
default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')
default_speaker.play(samples, samplerate=samplerate)
See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
add a comment |
This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.
import soundfile as sf
import soundcard as sc
default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')
default_speaker.play(samples, samplerate=samplerate)
See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.
This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.
import soundfile as sf
import soundcard as sc
default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')
default_speaker.play(samples, samplerate=samplerate)
See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.
edited Oct 12 '17 at 21:39
answered Oct 5 '17 at 21:40
n00pn00p
8118
8118
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
add a comment |
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
Just a headsup for anyone going for this (as I am). All the libs and their dependencies take forever to build on a Raspberry Pi 1B+ - especially numpy.
– pojda
Oct 14 '17 at 1:16
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
PS: this didn't work for raspberry pi "NotImplementedError: SoundCard does not support linux2 yet", and couldn't figure out a way to fix it. I'm going with os.system("mpg123 file.mp3")
– pojda
Oct 14 '17 at 2:42
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
Ah, that sucks. I guess raspberry pi is a somewhat special environment. Perhaps if you posted an issue on the issuetracker you could get it sorted out or fixed.
– n00p
Oct 14 '17 at 13:28
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
On further thought, perhaps the problem is that you are using an old kernel or old python version. With newer python versions that error should not look like that i think.
– n00p
Oct 15 '17 at 15:35
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
It's running Raspbian, which is basically a Debian Stretch fork. I gave up and went the os.system way which is working just fine atm. Thanks for helping me out!
– pojda
Oct 17 '17 at 19:00
add a comment |
To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.
from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])
It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.
add a comment |
To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.
from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])
It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.
add a comment |
To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.
from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])
It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.
To play a notification sound using python, call a music player, such as vlc. VLC prompted me to use its commandline version, cvlc, instead.
from subprocess import call
call(["cvlc", "--play-and-exit", "myNotificationTone.mp3"])
It requires vlc to be preinstalled on the device. Tested on Linux(Ubuntu 16.04 LTS); Running Python 3.5.
answered Feb 22 '18 at 13:10
amarVashishthamarVashishth
3812421
3812421
add a comment |
add a comment |
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
add a comment |
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
add a comment |
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
answered Nov 19 '18 at 21:15
Captain DjangoCaptain Django
115
115
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f260738%2fplay-audio-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown