Loading...
PHP, MySQL | Почему не загружает АУДИО
Вот код. ChatCPT постоянно забывает предыдущий код как и ответ соответственно

php
   <?php 

namespace App\Jobs\User\Timeline;

use Exception;
use App\Models\Post;
use Illuminate\Support\Str;
use FFMpeg\Format\Audio\Mp3;
use App\Constants\Filesystem;
use App\Enums\Post\PostStatus;
use App\Enums\Media\MediaStatus;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\User\Timeline\MediaProcessedEvent;
use App\Services\Filesystem\Upload\AudioUploadService;

class ConvertAndCompressPostAudio implements ShouldQueue
{
use Queueable;

public $timeout = (60 * 30); // 30 minutes

private $postData;

public function __construct(Post $postData)
{
$this->postData = $postData;
}

public function handle(): void
{
$postMedia = $this->postData->media()->first();

try {
$audioUploadService = app(AudioUploadService::class);
$postMedia = $this->postData->media()->first();

if (! $audioUploadService) {
throw new Exception('Required services are not available. Ensure that fileUploaderService and ffmpegService are properly injected.');
}

// Get audio local temporary path
$audioTempOldPath = $postMedia->source_path;

// Generate new audio temporary path for compressed audio marking it as compressed. [compressed.mp3]
$audioTempNewPath = $audioUploadService->generateAudioTemporaryFilePath("compressed.{$audioUploadService->audioDefaultExtension}");

$ffmpeg = $audioUploadService->getFFMpeg();
$audioOldAbsLocalPath = storage_local_path($audioTempOldPath);
$audioNewAbsLocalPath = storage_local_path($audioTempNewPath);

if(config('logging.debugging.audio_process_logging')) {
$fileOldExists = (file_exists($audioOldAbsLocalPath)) ? 'Yes' : 'No';

Log::info("Audio with path: {$audioOldAbsLocalPath} loaded. Audio file exists: {$fileOldExists}");
}

// Compress audio and save to new path converting it to mp3
$audio = $ffmpeg->open($audioOldAbsLocalPath);
$format = new Mp3();
$format = $format->setAudioKiloBitrate(128);

$audio->save($format, $audioNewAbsLocalPath);

if(file_exists($audioNewAbsLocalPath)) {

// Upload compressed audio to public disk and update post media
// Public disk is determined by post media with round robin algorithm
// and it is not local public folder of the application.

$audioFileDuration = $audioUploadService->getAudioDuration($audioTempNewPath);

$audioFilePath = $audioUploadService
->setNamespace(Filesystem::getPostAudioNamespace())
->setStorageDisk($postMedia->disk)
->upload($audioNewAbsLocalPath);

$audioFileSize = Storage::disk('local')->size($audioTempNewPath);
$mediaMetadata = $postMedia->metadata;
$newFilename = Str::beforeLast($mediaMetadata['file_name'], '.');

$mediaMetadata['duration'] = $audioFileDuration;
$mediaMetadata['file_name'] = "{$newFilename}.{$audioUploadService->audioDefaultExtension}";
$postMedia->source_path = $audioFilePath['audio_path'];
$postMedia->extension = $audioUploadService->audioDefaultExtension;
$postMedia->status = MediaStatus::PROCESSED;
$postMedia->metadata = $mediaMetadata;
$postMedia->size = $audioFileSize;
$postMedia->save();

$this->postData->status = PostStatus::ACTIVE;

$this->postData->save();

if(config('logging.debugging.audio_process_logging')) {
$fileNewExists = file_exists($audioNewAbsLocalPath) ? 'Yes' : 'No';

Log::info("Compressed audio with new path: {$audioNewAbsLocalPath} saved. Audio new file exists: {$fileNewExists}");
}

Storage::disk('local')->delete($audioTempOldPath);
Storage::disk('local')->delete($audioTempNewPath);

// Broadcast audio processed event with updated post media and user id
// to notify users that audio has been processed.

try {
event(new MediaProcessedEvent($postMedia->refresh(), $this->postData->user_id));
} catch (Exception $e) {
Log::error('Failed to broadcast audio processed event: ' . $e->getMessage());
}
}
}

catch (Exception $e) {
Log::error('Post audio processing failed after 5 attempts. Error: ' . $e->getMessage());

$this->fail();
}
}

public function tries(): int
{
return 5;
}
}
Ffmpeg установлена библиотека?
Тем более в методе, есть логирование ошибок, можно посмотреть
Лара (26 дек 2025, в 16:53)
Ffmpeg установлена библиотека?
Да.
20251226152444.png
20251226152444.png 220.8 Kb ⬇ 69
Лара , C:\OSPanel\home\colibri.local>php artisan
Laravel Framework 12.44.0
OZZY , что в файле для логов пишется?
[hljs class="php"]<?php

namespace App\Jobs\User\Timeline;

use Exception;
use App\Models\Post;
use Illuminate\Support\Str;
use FFMpeg\Format\Audio\Mp3;
use App\Constants\Filesystem;
use App\Enums\Post\PostStatus;
use App\Enums\Media\MediaStatus;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Events\User\Timeline\MediaProcessedEvent;
use App\Services\Filesystem\Upload\AudioUploadService;

class ConvertAndCompressPostAudio implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public $timeout = 1800; // 30 minutes

public function __construct(public Post $postData)
{
}

public function handle(AudioUploadService $audioUploadService): void
{
$postMedia = $this->postData->media()->first();

// temp paths (relative paths in local disk)
$audioTempOldPath = null;
$audioTempNewPath = null;

try {
if (! $postMedia) {
throw new Exception('Post has no media to process.');
}

if (empty($postMedia->source_path)) {
throw new Exception('Post media source_path is empty.');
}

$audioTempOldPath = $postMedia->source_path;

// Генерим новый временный путь (local disk)
$audioTempNewPath = $audioUploadService->generateAudioTemporaryFilePath(
"compressed.{$audioUploadService->audioDefaultExtension}"
);

$ffmpeg = $audioUploadService->getFFMpeg();

// Абсолютные пути на local disk
$audioOldAbsLocalPath = Storage::disk('local')->path($audioTempOldPath);
$audioNewAbsLocalPath = Storage::disk('local')->path($audioTempNewPath);

if (config('logging.debugging.audio_process_logging')) {
Log::info("Audio old local path: {$audioOldAbsLocalPath}; exists: " . (file_exists($audioOldAbsLocalPath) ? 'Yes' : 'No'));
}

if (! file_exists($audioOldAbsLocalPath)) {
throw new Exception("Source audio file not found on local disk: {$audioOldAbsLocalPath}");
}

// Конвертация/сжатие в mp3 128kbps
$audio = $ffmpeg->open($audioOldAbsLocalPath);

$format = (new Mp3())->setAudioKiloBitrate(128);

$audio->save($format, $audioNewAbsLocalPath);

if (! file_exists($audioNewAbsLocalPath)) {
throw new Exception("Compressed audio file was not created: {$audioNewAbsLocalPath}");
}

// Длительность (если ваш сервис ожидает relative path — передаем $audioTempNewPath)
$audioFileDuration = $audioUploadService->getAudioDuration($audioTempNewPath);

// Загрузка в нужный диск (round robin у вас внутри по $postMedia->disk)
$audioFilePath = $audioUploadService
->setNamespace(Filesystem::getPostAudioNamespace())
->setStorageDisk($postMedia->disk)
->upload($audioNewAbsLocalPath);

if (empty($audioFilePath['audio_path'])) {
throw new Exception('Upload service did not return audio_path.');
}

// Размер сжатого файла
$audioFileSize = Storage::disk('local')->exists($audioTempNewPath)
? Storage::disk('local')->size($audioTempNewPath)
: null;

$mediaMetadata = $postMedia->metadata ?? [];
$oldFileName = $mediaMetadata['file_name'] ?? null;
$newFilename = $oldFileName ? Str::beforeLast($oldFileName, '.') : 'audio';

$mediaMetadata['duration'] = $audioFileDuration;
$mediaMetadata['file_name'] = "{$newFilename}.{$audioUploadService->audioDefaultExtension}";

$postMedia->source_path = $audioFilePath['audio_path'];
$postMedia->extension = $audioUploadService->audioDefaultExtension;
$postMedia->status = MediaStatus::PROCESSED;
$postMedia->metadata = $mediaMetadata;

if ($audioFileSize !== null) {
$postMedia->size = $audioFileSize;
}

$postMedia->save();

$this->postData->status = PostStatus::ACTIVE;
$this->postData->save();

if (config('logging.debugging.audio_process_logging')) {
Log::info("Audio compressed local path: {$audioNewAbsLocalPath}; exists: " . (file_exists($audioNewAbsLocalPath) ? 'Yes' : 'No'));
}

// Событие
try {
event(new MediaProcessedEvent($postMedia->refresh(), $this->postData->user_id));
} catch (Exception $e) {
Log::error('Failed to broadcast audio processed event: ' . $e->getMessage());
}
} catch (Exception $e) {
Log::error('Post audio processing failed. Error: ' . $e->getMessage(), [
'post_id' => $this->postData->id ?? null,
'media_id' => $postMedia->id ?? null,
]);

// чтобы очередь пометила как failed корректно
$this->fail($e);
} finally {
// чистим временные файлы, но аккуратно
if ($audioTempOldPath && Storage::disk('local')->exists($audioTempOldPath)) {
Storage::disk('local')->delete($audioTempOldPath);
}
if ($audioTempNewPath && Storage::disk
________
посл. ред. 26.12.2025 в 18:26; всего 2 раз(а); by Html
Лара (26 дек 2025, в 17:48)
OZZY , что в файле для логов пишется?
Нету в логах ничего. Просто файлы аудио и видео не загружаются на сервер. Висит как на скрине вот и все.
20251227083345.png
20251227083345.png 17.8 Kb ⬇ 61
Лара , Накатил Google Antigravity , что-то там копается в коде.
Лара , Короче Гугл Антигравити мне все починил. Я вахуе если честно. И видео, и аудио.. все работает
20251228175907.png
20251228175907.png 137.8 Kb ⬇ 58
Онлайн: 4
Время:
Gen. 0.1053
(c) Bym.Guru 2010-2026