💽 Windows

from ctypes import create_unicode_buffer, windll, wintypes
import time
windll.winmm.mciSendStringW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.UINT, wintypes.HANDLE]
windll.winmm.mciGetErrorStringW.argtypes = [wintypes.DWORD, wintypes.LPWSTR, wintypes.UINT]

def winCommand(*command):
    buf = create_unicode_buffer(600)
    windll.winmm.mciSendStringW(' '.join(command), buf, 599, 0)
    return buf.value

musicURL = r"C:\Users\EpicCodeWizard\Downloads\in.wav"
songLenght = 9999
try:
    winCommand('open ' + musicURL)
    winCommand('play ' + musicURL)
    time.sleep(songLenght)
finally:
    winCommand('close ' + musicURL)

I have a windows computer, so this was easy to test. Using the windll.winmm library, this library can play sound. The sound plays asynchronously, so if the program doesn't sleep or do something else, the program will end, ending the music. This only works on wav, I am working on all file types.

💾 MacOS

import shlex
import sys
import os

if sys.version_info[0] == 2:
    try:
        from AppKit import NSSound
    except ImportError:
        sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC')
        from AppKit import NSSound

    from Foundation import NSURL
    from time import sleep

    musicURL = "in.mp3"
    if '://' not in musicURL:
        if not musicURL.startswith('/'):
            from os import getcwd
            musicURL = getcwd() + '/' + musicURL
        musicURL = 'file://' + musicURL
    try:
        musicURL.encode('ascii')
        musicURL = musicURL.replace(' ', '%20')
    except UnicodeEncodeError:
        from urllib import quote
        parts = musicURL.split('://', 1)
        musicURL = parts[0] + '://' + quote(parts[1].encode('utf-8')).replace(' ', '%20')

    url = NSURL.URLWithString_(musicURL)
    for i in range(5):
        nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True)
        break
    nssound.play()
    import time
    time.sleep(nssound.duration())
else:
    musicURL = "in.wav"
    os.system('/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python ' + shlex.quote(os.path.dirname(os.path.abspath(__file__))) + '/' + __file__ + ' ' + shlex.quote(musicURL), shell=True)

I have an old Mac sitting at home, so I decided to use it. Instead of trying to use executables or other libraries, I just call the music from the pre-installed python 2.7. The python has PyObjC, so we don't need the user to install it. After 3 hours of hardwork, I finally got it to work.

Built With

Share this project:

Updates