Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set output device for pygame mixer

I need to play audio files through different audio devices using pygame. Apparently this is possible by parameter devicename in method pygame.mixer.init(), but there is no documentation for it.

My questions:

1- How to set output device for pygame mixer (or channel/sound if possible)?

2- How to list all available device-names?

like image 611
h.nodehi Avatar asked Jul 18 '19 16:07

h.nodehi


People also ask

Does pygame mixer support MP3?

Pygame can load WAV, MP3, or OGG files. The difference between these audio file formats is explained at http://invpy.com/formats. To play this sound, call the Sound object's play() method. If you want to immediately stop the Sound object from playing call the stop() method.

What is pygame mixer sound?

mixer pygame module for loading and playing sounds is available and initialized before using it. The mixer module has a limited number of channels for playback of sounds. Usually programs tell pygame to start playing audio and it selects an available channel automatically.


1 Answers

I found the solution. Pygame v2 has made all of this possible. Since pygame uses sdl2, we can get audio device names by pygame's own implementation of the sdl2 library.

To get audio device names:

import pygame._sdl2 as sdl2

pygame.init()
is_capture = 0  # zero to request playback devices, non-zero to request recording devices
num = sdl2.get_num_audio_devices(is_capture)
names = [str(sdl2.get_audio_device_name(i, is_capture), encoding="utf-8") for i in range(num)]
print("\n".join(names))
pygame.quit()

On my device, the code returns:

HDA Intel PCH, 92HD87B2/4 Analog
HDA Intel PCH, HDMI 0
C-Media USB Headphone Set, USB Audio

And to set the output audio device for pygame mixer:

import pygame
import time

pygame.mixer.pre_init(devicename="HDA Intel PCH, 92HD87B2/4 Analog")
pygame.mixer.init()
pygame.mixer.music.load("audio.ogg")
pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.quit()
like image 110
h.nodehi Avatar answered Oct 23 '22 01:10

h.nodehi