Dualshock 4 windows звук

Выбирая геймпад для своего компьютера, я остановился на DualShock4, так как мне понравилась идея, что можно будет слушать аудио через подключаемые к нему наушники. Но после покупки я узнал, что, оказывается, никто не знает, как передать звук на геймпад через Bluetooth. Поэтому я решил разобраться с данным вопросом. Если вам интересно узнать, как DualShock4 общается с игровой консолью, жду под катом.

К сожалению, у меня нет PlayStation 4, поэтому пришлось довольствоваться только выложенными в Интернете дампами, а также уже известными фрагментами обмена.
В процессе изучения темы мне очень помогла вот эта страница. В ней описаны основные моменты передачи данных между консолью и геймпадом, а также выложен дамп этих данных. Нас интересует файл дампа с именем ds4_uart_hci_cap_playroom_needs_sorting.pcap.gz. Открываем его в Wireshark и начинаем изучать. Отсортируем пакеты по времени, так как, видимо, дамп записывался отдельно на приём и передачу. Дамп снимался напрямую с UART геймпада, после чего был сконвертирован в pcap.

В начале идёт настройка самого модуля Bluetooth. Далее, с №49-го по №163-й пакет, идёт установка соединения и настройка канала передачи. Очень хорошо этот процесс описан в статье Беспроводной звук. Часть 1. Препарируем Bluetooth.
Но для нашей задачи это неособо важно.

После всех «подготовительных работ» геймпад начинает отправлять HID Report. Формат сообщения описан на вики странице. Первый пакет с данными от консоли — это пакет №70181. Давайте разберём его, пользуясь данными с вики страницы.
Нас интересуют только данные, которые передаются через HID Profile.
Вот его содержание.

Номер байта bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
[0] 0x0a – Тип Data 0x00 — Зарезервировано 0x02 — Направление передачи
[1] 0x11 – Код операции
[2 — 3] Неизвестно
[4] 0xf0 Запрещает изменение данных у геймпада, 0xf3 Разрешает изменение
[5 — 6] Неизвестно
[7] Rumble (right / weak)
[8] Rumble (left / strong)
[9] RGB color (Red)
[10] RGB color (Green)
[11] RGB color (Blue)
[12-24] Неизвестно
[25] Громкость звучания в %
[26 — 74] Неизвестно
[75 — 78] CRC-32 от предыдущих данных

Хотя 26 байт помечен на упомянутой выше странице как неизвестный, во время моих экспериментов удалось выяснить, что он отвечает за громкость звучания и выставляется в процентах. Также хотя поле crc присутствует, но геймпад его не проверяет и можно просто отправлять нулевое значение.

Так как нам интересно, какие данные передаёт консоль, давайте отфильтруем их по 0-му байту HID Profile, который поможет нам определить направление пакета. Данные от гемпада имеют значение 0xa1, от консоли 0xa2. Фильтр для Wireshark получится таким: bthid[0] == 0xa2.

Если прокрутить пакеты, то, начиная с пакета №98516, сильно увеличился размер данных. Если судить по данным с вики страницы, то начало у пакетов с кодом операции 0x15 и 0x19 такое же, как и у 0x11, только без CRC, которая находится в конце.

Всё есть HID

Вот мы и подошли к самому интересному — как передать звук на геймпад. Вот как выглядит пакет с аудиоданными.

Если внимательно посмотреть на пакеты с кодами операции 0x14, 0x15, 0x17, 0x19, то заметно некое постоянство, а именно идущие подряд байты 0x9c, 0x75, 0x19. Это очень похоже на Bluetooth SBC header ( SBC — это один из стандартных кодеков для передачи аудио по Bluetooth). И хотя для передачи SBC по Bluetooth есть стандарт A2DP, создатели PS4 решили пойти по своему пути и передавать звук прямо в HID сообщениях. Также если посмотреть пакеты дальше то видно, что также меняются два байта перед Bluetooth SBC header, это счётчик фреймов. Давайте проверим наше предположение, что это стандартный SBC кодек. Для этого воспользуемся следующим скриптом на Python.

#!/usr/bin/env python3

from pcapfile import savefile
import collections
import struct

class bluetooth(object):

	def __init__(self, packet, number):
		self.direction = packet.raw()[3]
		self.payload = packet.raw()[4:]
		self.time = ((packet.timestamp_ms-444738)/1000000)+(packet.timestamp-3)
		self.number = number


pcap = savefile.load_savefile(open('ds4_uart_hci_cap_playroom_needs_sorting.pcap', 'rb'))


bluetooth_packet = []
number=1
for pkt in pcap.packets:
	bluetooth_packet.append(bluetooth(pkt, number))
	number+=1

sbc = open('test.sbc', 'wb')
bluetooth_packet.sort(key=lambda pkt: pkt.time)
count = 0
for bt in bluetooth_packet:
	count+=1
	if(bt.payload[0]==2):
		l2cap_len = struct.unpack("<H",bt.payload[5:7])[0]
		if(l2cap_len>5):
			sony_opcode = bt.payload[10]
			if(sony_opcode == 0x19):
				sbc.write(bt.payload[0x5b:-0x12])

			if(sony_opcode == 0x17):
				sbc.write(bt.payload[0x10:-0x8])

			if(sony_opcode == 0x15):
				sbc.write(bt.payload[0x5b:-0x1D])

			if(sony_opcode == 0x14):
				sbc.write(bt.payload[0x10:-0x28])

Скрипт работает следующим образом: открываем дамп, кладем все пакеты в список, после чего сортируем по времени. Затем проходим по порядку все пакеты, доставая аудиоданные из сообщений с кодом операции 0x19,0x17,0x15 и 0x14 и записывая их в файл.

Теперь попробуем воспроизвести получившийся файл, для чего воспользуемся gstreamer’ом:

gst-launch-1.0 filesrc location=test.sbc ! sbcparse ! sbcdec ! autoaudiosink

В начале файла будет тишина (это видно и по сохраненным данным). Для удобства преобразуем данные в wav:

gst-launch-1.0 filesrc location=test.sbc ! sbcparse ! sbcdec ! audioconvert ! wavenc ! filesink location=output.wav

Еесли перемотать на 41 секунду получившийся wav, мы услышим звук.
Таким образом, мы удостоверились, что DualShock4 использует обычное SBC кодирование для передачи звука.

Теперь интересно попробовать самим сгенерировать данные для воспроизведения на геймпаде.
Воспользуемся для этого всё теми же инструментами. Gstreamer будет кодировать, а Python будет будет передавать данные на DualShock4.
В Linux можно очень просто работать с геймпадом благодаря тому, что в нём всё (включая устройства) является файлами.
Узнать, какой файл соответствует геймпаду, можно после сопряжения DualShock4 с компьютером. В результате удачного сопряжения в выводе dmesg появится строка
sony 0005:054C:05C4.0007: input,hidraw5: BLUETOOTH HID v1.00 Gamepad [Wireless Controller]
Значит, наш контроллер присутствует в системе в виде файла с именем /dev/hidraw5, и мы можем передавать данные на геймпад, просто записывая необходимые данные в этот файл.
Вот скрипт, с помощью которого это можно делать:

#!/usr/bin/env python3
import struct
from sys import stdin
import os
from io import FileIO

hiddev = os.open("/dev/hidraw5", os.O_RDWR | os.O_NONBLOCK)
pf = FileIO(hiddev, "wb+", closefd=False)
#pf=open("ds_my.bin", "wb+")

rumble_l = 0
rumble_r = 0
r = 0
g = 0
b = 50
crc = 0
volume = 50
flash_bright = 150
flash_dark = 150


def frame_number(inc):
	res = struct.pack("<H", frame_number.n)
	frame_number.n += inc
	if frame_number.n > 0xffff:
		frame_number.n = 0
	return res
frame_number.n = 0

def joy_data():
	data = [0xf3,0x4,0x00]
	data.extend([rumble_l,rumble_r,r,g,b,flash_bright,flash_dark])
	data.extend([0]*8)
	data.extend([0x43,0x43,0x00,volume,0x85])
	return data

def _11_report():
	data = joy_data()
	data.extend([0]*(48))
	data.append(crc)
	return bytearray(data)

def _14_report(audo_data):
	return b'\x14\x40\xA0'+ frame_number(2) + b'\x02'+ audo_data + bytearray(40)

def _15_report(audo_data):
	data = joy_data();
	data.extend([0]*(52))
	return b'\x15\xC0\xA0' + bytearray(data)+ frame_number(2) + b'\x02' + audo_data + bytearray(29)

def _17_report(audo_data):
	return b'\x17\x40\xA0' + frame_number(4) + b'\x02' + audo_data + bytearray(8)

stdin = stdin.detach()
data = bytearray()
count = 1
while True:
#	if count % 200:
	if True:
		data = _14_report(stdin.read(224)) if count % 3 else _15_report(stdin.read(224))
	else:
		data = _17_report(stdin.read(448))
		print('big')
	count+=1

	pf.write(data)

Скрипт читает из стандартного потока закодированные в SBC аудиоданные и формирует два типа пакетов 0x14 и 0x15 (также комментированием/раскомментированием строк можно включить формирование увеличенного в два раза пакета с опкодом 0x17) и отправляет их на геймпад путем записи в hidraw девайс.
Попробуем использовать этот скрипт, чтобы проиграть тестовый звуковой сигнал.
Данный сигнал будет генерироваться при помощи gstreamer и отправляться на стандартный поток вывода, откуда его будет забирать скрипт.

gst-launch-1.0 -q audiotestsrc is-live=true ! sbcenc ! 'audio/x-sbc,channels=2,rate=32000,channel-mode=dual,blocks=16,subbands=8,bitpool=25' ! queue ! fdsink | ./play.py

И у нас получилось

(почти). Звук идет, но периодически слышны небольшие заикания. С чем они связаны, я понять так и не смог. Возможно, я не совсем правильно работаю с hid устройством в linux — если кто-нибудь сможет подсказать, как сделать правильнее, я буду благодарен. Попытка испопользования Bluetooth сокета успехом также не увенчалась — через полсекунды проигрывания звука всё заканчивалось

(Смотри UPD).

Заключение

Хотелось бы выразить благодарность таким проектам, как DS4Windows и ds4drv.
Данные проекты позволяют использовать геймпад на компьютере. Надеюсь, эта статья поможет добавить также и поддержку передачи звука в эти проекты.

Спасибо за внимание.

UPD:
Небольшие дополнение.
Если добавить is-live=true к audiotestsrc то звук идет почти без заиканий.
Вот полезный pipeline для gstreamer который позволяет захватывать все, что идет на аудио выход и отправлять на DualShock4.

gst-launch-1.0 -q pulsesrc device="alsa_output.pci-0000_00_1b.0.analog-stereo.monitor" ! queue ! audioresample ! 'audio/x-raw,rate=32000' ! audioconvert ! sbcenc ! 'audio/x-sbc,channels=2,rate=32000,channel-mode=dual,blocks=16,subbands=8,bitpool=25' ! queue ! fdsink | ./play.py

Получить имя девайса можно следующей командой.
pacmd list-sources | grep -e device.string -e 'name:'

General info

Some official and third-party DualShock 4 and DualSense gamepads support audio input/output when connected to the PC via specific connection methods (mostly USB only). This page is dedicated on instructing users on how to fix some «issues» that might happen when connecting their gamepads to the PC and leave some comments

List of gamepads that support audio input/output on PC

  • DualShock 4 (version 2 only) connected via USB
  • DualShock 4 connected via Sony’s USB wireless adapter
  • DualSense connected via USB
  • Possibly DualShock 4 copy-cats via USB (rare situation, most don’t have any working audio functions when used on PC)

Switching between audio devices on Windows and applications

Switching audio devices in common system and apps settings

Important

  • If you are on Windows 11 some images may differ from your experience, but similar options should be found in similar places
  • It’s impossible to cover all apps here, so use your common sense and try to find the audio settings on the app you are using yourself
  • Some apps don’t have their specific audio settings and use what is defined on Windows’ audio settings
    • Upon changing Windows’ audio settings the app may need to be restarted

Windows Taskbar (headphone/speakers only)

WindowsAudioTaskbar

Windows Settings

WindowsAudioSettings.png

Discord…

Settings

DiscordAudioSettings.png

Quick switch

  • Right click on the headphone or mic icons:

DiscordAudioQuickSwitch.png

Common issues

PC’s own headphone/speaker or mic stop working when connecting a DualShock 4 or DualSense to the PC

Because some gamepads expose their headphone and mic jack when connected (check the list above on this page) Windows may be auto-switching to them as the new computer’s default.

The «fix» is instructing Windows or the application being used (Discord, Skype, some games that support audio communication) to switch back specifically to the desired headphone/mic. Have a look at the «switching between audio devices» section on this page.

Headphone or headset doesn’t work when connected via the gamepad

Things to check:

  1. Do you have a controller that has audio support when connected to the PC according to the list on this page? Is it connected by one of the supported methods also described on the list?
    • Remember, currently no official gamepad exposed its audio functions when connected through Windows’ Bluetooth
  2. Have you selected the gamepad’s headphone or mic as the desired audio devices accordingly to the «Switching between audio devices» section?

If everything looks OK but the headphone/mic still isn’t working then… Don’t know, sorry. Maybe the headphone jack port is broken or you are suffering from some poor contact?

Frequently Asked Questions

«Can I use my DS4/DualSense’s headphone jack when connected via the standard Windows Bluetooth?»

No, this feature is not implemented. Is it possible to implement this? Apparently yes. WILL it be implemented? The answer is probably no unless some new developer steps in to specifically focus on this.

What most users don’t understand is that:

  • DS4Windows is a free, open-source software developed by a few people out of their own limited free time. Have you ever had to work, study, have fun and still have time left to work on non-paid software for random internet users? Balancing all these things is not an easy task
  • Even minor things can be complicated to be implemented. Audio input/output over Bluetooth is complicated, specifically because there is a LOT that is not known for the lack of documentation, so sometimes it takes way too many hours of work just to test something
  • There are other more important things to focus that actually impact gaming. if users need wireless headsets they can just buy a dedicated one. As such, this niche feature is really low on the To Do list


Readers help support Windows Report. We may get a commission if you buy through our links.

Read our disclosure page to find out how can you help Windows Report sustain the editorial team. Read more

As PS4‘s controller, DualShock 4 isn’t made to work on a Windows PC by default; you need to install the right drivers to make the connection. 

Users have been reporting a specific issue with the audio driver that causes many issues. For example, Windows tends to recognize the controller as an audio device, automatically disabling the default audio hardware.

So, we’ll try to offer a few solutions for this and all other audio driver-related issues with the DualShock 4 controller in Windows 10.

How to fix DualShock 4 audio driver issues in Windows 10?

1. Reinstall the controller

  1. Go to Settings Devices.
    bluetooth devices ps4 controller audio driver windows 10

  2. You should see the DualShock 4 controller under Other devices.
  3. Left-click it, and go to Remove device.
  4. Unplug the controller, and re-connect it again.
  5. It should look for new drivers automatically. Wait for the drivers to install, and the controller should work now.

2. Update drivers

  1. Right-click the Start and select Device Manager.
  2. Navigate to Universal Serial Bus controllers and expand this section.
    device manager ps4 controller audio driver windows 10

  3. Right-click your controller and open Properties.
  4. Select the Details tab.
  5. From the drop-down menu, open HardwareIds.
  6. Copy the first row and paste it into your browser’s address bar.
  7. The search results should show you the exact drivers you’ll need to install.

Updating drivers can also help you with issues like can’t connect 2 DualShock controllers on your PC; read this to learn more.

2.1 Update drivers automatically

Another solution is to update your drivers using a specialized driver updater tool. A dedicated tool is very easy to use and allows you to update the drivers fast and safely. Such a tool is always a better solution when you have never experienced driver updating.

3. Use the Bluetooth troubleshooter

  1. Open the Settings app and go to Update & Security section.
  2. Select Troubleshoot from the menu on the left.
  3. Select Bluetooth from the right pane and click Run the troubleshooter.
    bluetooth troubleshooter ps4 controller audio driver windows 10

  4. Follow the instructions on the screen to complete the troubleshooter.
Read more about this topic

  • Best Tools To Lower Ping And Lag In Online Games [2025 tested]
  • 5 Classic Windows Games That Never Get Old
  • Avowed Keeps Crashing: How to Permanently Stop it
  • What is Avowed Install Size For Xbox & PC

4. Run the Sound troubleshooter

  1. Open the Settings app and go to Update & Security section.
  2. Select Troubleshoot from the menu on the left.
  3. Select Playing Audio from the right pane and click Run the troubleshooter.
    playing audio troubleshooter ps4 controller audio driver windows 10

  4. Follow the instructions on the screen to complete the troubleshooter.

Let us know how the procedure went for you in the comments area below.


Ivan Jenic

Windows Hardware Expert

Passionate about all elements related to Windows and combined with his innate curiosity, Ivan has delved deep into understanding this operating system, with a specialization in drivers and driver troubleshooting.

When he’s not tackling diverse driver-related problems, Ivan enjoys watching good movies and spending time hiking with his family and friends.


This page is mainly focused on troubleshooting audio issues such as your headphone and mic not working.

General Info

Some official and third-party DualShock 4 and DualSense gamepads support audio input/output when connected to the PC via specific connection methods (mostly USB only). This page is dedicated on instructing users on how to fix some “issues” that might happen when connecting their gamepads to the PC and leave some comments

List of gamepads that support audio input/output on PC

  • DualShock 4 (version 2 only) connected via USB
  • DualShock 4 connected via Sony’s USB wireless adapter
  • DualSense connected via USB
  • Possibly DualShock 4 copy-cats via USB (rare situation, most don’t have any working audio functions when used on PC)

Switching between audio devices on Windows and applications

Important


If you are on Windows 11 some images may differ from your experience, but similar options should be found in similar places
It’s impossible to cover all apps here, so use your common sense and try to find the audio settings on the app you are using yourself
Some apps don’t have their specific audio settings and use what is defined on Windows’ audio settings
Upon changing Windows’ audio settings the app may need to be restarted

Windows Taskbar (headphone/speakers only)

Windows Taskbar (headphone/speakers only)

Quick switch

  • Right click on the headphone or mic icons:

Common issues

PC’s own headphone/speaker or mic stop working when connecting a DualShock 4 or DualSense to the PC

Because some gamepads expose their headphone and mic jack when connected (check the list above on this page) Windows may be auto-switching to them as the new computer’s default.

The “fix” is instructing Windows or the application being used (Discord, Skype, some games that support audio communication) to switch back specifically to the desired headphone/mic. Have a look at the “switching between audio devices” section on this page.

Headphone or headset doesn’t work when connected via the gamepad

Things to check:

  1. Do you have a controller that has audio support when connected to the PC according to the list on this page? Is it connected by one of the supported methods also described on the list?
    • Remember, currently no official gamepad exposed its audio functions when connected through Windows’ Bluetooth
  2. Have you selected the gamepad’s headphone or mic as the desired audio devices accordingly to the “Switching between audio devices” section?

If everything looks OK but the headphone/mic still isn’t working then… Don’t know, sorry. Maybe the headphone jack port is broken or you are suffering from some poor contact?

Frequently Asked Questions

Can I use my DS4/DualSense’s headphone jack when connected via the standard Windows Bluetooth?

No, this feature is not implemented. Is it possible to implement this? Apparently yes. WILL it be implemented? The answer is probably no unless some new developer steps in to specifically focus on this.

What most users don’t understand is that:

  • DS4Windows is a free, open-source software developed by a few people out of their own limited free time. Have you ever had to work, study, have fun and still have time left to work on non-paid software for random internet users? Balancing all these things is not an easy task
  • Even minor things can be complicated to be implemented. Audio input/output over Bluetooth is complicated, specifically because there is a LOT that is not known for the lack of documentation, so sometimes it takes way too many hours of work just to test something
  • There are other more important things to focus that actually impact gaming. if users need wireless headsets they can just buy a dedicated one. As such, this niche feature is really low on the To Do list

Table of Contents

Регистрация

Пожалуйста, введите Ваш e-mail, чтобы зарегистрироваться.
Регистрируясь на нашем сайте вы соглашаетесь с правилами и политикой конфиденциальности.

Получать новости

Восстановление доступа к аккаунту

Пожалуйста, введите Ваш e-mail, чтобы начать процедуру восстановления.

Изменение почты

Пожалуйста, введите Ваш e-mail, чтобы начать процедуру восстановления.

Код подтверждения

Письмо с проверочным кодом было отправлено на ваш e-mail: . Введите код в поле ниже.

Не получили письмо? Не забудьте заглянуть в папку со спамом и проверить правильно ли указан адрес электронной почты.

Повторная отправка письма возможна через: 01:00

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Программа для нахождения драйверов на windows 10
  • На чем написать программу для windows
  • Как выйти из режима обновления windows
  • Обновление для windows 11 для amd
  • Как делать бэкап на windows 11