pythonblobwavsoundfile

soundfile.LibsndfileError: Error opening Format not recognised. error in python


i want audio blob data send to python server and the python server combine two wav files at the test soundfile.LibsndfileError: Error opening Format not recognised. error is occurred here is the server with fastapi socketio

@sio.on('voice')
def get_chunk(sid, chunk: bytes):
    
    directory = str("dddd")
    if not os.path.exists(directory):
        os.makedirs(directory)
    
    file_path = os.path.join(directory, f'{sid}.wav')
    file_path_chunk =  os.path.join(directory, f'{sid}_chunk.wav')
    outfile =  os.path.join(directory, f'{sid}_result.wav')

    if not os.path.exists(file_path):  # 처음 보낼 경우 => 합칠 필요 없음 
        with open(file_path, 'wb+') as file:
            file.write(chunk)
    else:
        with open(file_path_chunk, 'wb+') as file:
            file.write(chunk)

        try:
            # 원본 파일 읽기
            data, samplerate = soundfile.read(file_path)
            # 새로운 chunk 파일 읽기
            chunk_data, _ = soundfile.read(file_path_chunk)
            # 읽은 chunk를 원본 파일에 추가
            data = np.concatenate([data, chunk_data])

            # 합쳐진 데이터를 결과 파일에 쓰기
            soundfile.write(outfile, data, samplerate)
        finally:
            # 처리가 끝나면 chunk 파일 삭제
            os.remove(file_path_chunk)

and here is the client code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>마이크 테스트</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.2/socket.io.js"></script>
</head>

<body>
    <input type=checkbox id="chk-hear-mic"><label for="chk-hear-mic">마이크 소리 듣기</label>
    <button id="record">녹음</button>
    <button id="stop">정지</button>
    <div id="sound-clips"></div>
    <script>
        var socket = io('http://127.0.0.1:5000');
        const record = document.getElementById("record")
        const stop = document.getElementById("stop")
        const soundClips = document.getElementById("sound-clips")
        const chkHearMic = document.getElementById("chk-hear-mic")

        const audioCtx = new(window.AudioContext || window.webkitAudioContext)() // 오디오 컨텍스트 정의

        const analyser = audioCtx.createAnalyser()
        //        const distortion = audioCtx.createWaveShaper()
        //        const gainNode = audioCtx.createGain()
        //        const biquadFilter = audioCtx.createBiquadFilter()

        function makeSound(stream) {
            const source = audioCtx.createMediaStreamSource(stream)
            socket.connect()
            source.connect(analyser)
            //            analyser.connect(distortion)
            //            distortion.connect(biquadFilter)
            //            biquadFilter.connect(gainNode)
            //            gainNode.connect(audioCtx.destination) // connecting the different audio graph nodes together
            analyser.connect(audioCtx.destination)

        }

        if (navigator.mediaDevices) {
            console.log('getUserMedia supported.')

            const constraints = {
                audio: true
            }
            let chunks = []

            navigator.mediaDevices.getUserMedia(constraints)
                .then(stream => {

                    const mediaRecorder = new MediaRecorder(stream)
                    
                    chkHearMic.onchange = e => {
                        if(e.target.checked == true) {
                            audioCtx.resume()
                            makeSound(stream)
                        } else {
                            audioCtx.suspend()
                        }
                    }
                    
                    record.onclick = () => {
                        mediaRecorder.start()
                        console.log(mediaRecorder.state)
                        console.log("recorder started")
                        record.style.background = "red"
                        record.style.color = "black"
                    }

                    stop.onclick = () => {
                        mediaRecorder.stop()
                        console.log(mediaRecorder.state)
                        console.log("recorder stopped")
                        record.style.background = ""
                        record.style.color = ""
                    }

                    mediaRecorder.onstop = e => {
                        console.log("data available after MediaRecorder.stop() called.")

                        const clipName = prompt("오디오 파일 제목을 입력하세요.", new Date())

                        const clipContainer = document.createElement('article')
                        const clipLabel = document.createElement('p')
                        const audio = document.createElement('audio')
                        const deleteButton = document.createElement('button')

                        clipContainer.classList.add('clip')
                        audio.setAttribute('controls', '')
                        deleteButton.innerHTML = "삭제"
                        clipLabel.innerHTML = clipName

                        clipContainer.appendChild(audio)
                        clipContainer.appendChild(clipLabel)
                        clipContainer.appendChild(deleteButton)
                        soundClips.appendChild(clipContainer)

                        audio.controls = true
                        const blob = new Blob(chunks, {
                            'type': 'audio/ogg codecs=opus'
                        })

                        chunks = []
                        const audioURL = URL.createObjectURL(blob)
                        audio.src = audioURL
                        console.log("recorder stopped")

                        deleteButton.onclick = e => {
                            evtTgt = e.target
                            evtTgt  .parentNode.parentNode.removeChild(evtTgt.parentNode)
                        }
                    }

          
                })
                .catch(err => {
                    console.log('The following error occurred: ' + err)
                })
        }
    </script>
</body></html>

and then error code

Task exception was never retrieved
future: <Task finished name='Task-29' coro=<InstrumentedAsyncServer._handle_event_internal() done, defined at F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_admin.py:274> exception=LibsndfileError(1, "Error opening 'dddd\\\\-dZWDNG1oD_HKvhjAAAB.wav': ")>
Traceback (most recent call last):
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_admin.py", line 276, in _handle_event_internal
    ret = await self.sio.__handle_event_internal(server, sid, eio_sid,
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_server.py", line 597, in _handle_event_internal
    r = await server._trigger_event(data[0], namespace, sid, *data[1:])
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_server.py", line 635, in _trigger_event
    ret = handler(*args)
          ^^^^^^^^^^^^^^
  File "f:\fastapi-socketio-wb38\Python-Javascript-Websocket-Video-Streaming--main\ppom.py", line 160, in get_chunk
    data, samplerate = soundfile.read(file_path)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 285, in read
    with SoundFile(file, 'r', samplerate, channels,
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 658, in __init__
    self._file = self._open(file, mode_int, closefd)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 1216, in _open
    raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
soundfile.LibsndfileError: Error opening 'dddd\\-dZWDNG1oD_HKvhjAAAB.wav': Format not recognised.
Task exception was never retrieved
future: <Task finished name='Task-32' coro=<InstrumentedAsyncServer._handle_event_internal() done, defined at F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_admin.py:274> exception=LibsndfileError(1, "Error opening 'dddd\\\\-dZWDNG1oD_HKvhjAAAB_chunk.wav': ")>
Traceback (most recent call last):
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_admin.py", line 276, in _handle_event_internal
    ret = await self.sio.__handle_event_internal(server, sid, eio_sid,
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_server.py", line 597, in _handle_event_internal
    r = await server._trigger_event(data[0], namespace, sid, *data[1:])
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\socketio\async_server.py", line 635, in _trigger_event
    ret = handler(*args)
          ^^^^^^^^^^^^^^
  File "f:\fastapi-socketio-wb38\Python-Javascript-Websocket-Video-Streaming--main\ppom.py", line 166, in get_chunk
    data, samplerate = soundfile.read(file_path_chunk)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 285, in read
    with SoundFile(file, 'r', samplerate, channels,
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 658, in __init__
    self._file = self._open(file, mode_int, closefd)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\fastapi-socketio-wb38\.vent\Lib\site-packages\soundfile.py", line 1216, in _open
    raise LibsndfileError(err, prefix="Error opening {0!r}: ".format(self.name))
soundfile.LibsndfileError: Error opening 'dddd\\-dZWDNG1oD_HKvhjAAAB_chunk.wav': Format not recognised.

the wav file is save in directory but the file can not opend, my eng is so bad. i apologize.


Solution

  • The error is inside the get_chunk() method. The issue is that the try except block doesn't have an except parameter and is useless. Try-Except Documentation

    I suggest converting the code to this:

        try:
            # 원본 파일 읽기
            data, samplerate = soundfile.read(file_path)
            # 새로운 chunk 파일 읽기
            chunk_data, _ = soundfile.read(file_path_chunk)
            # 읽은 chunk를 원본 파일에 추가
            data = np.concatenate([data, chunk_data])
    
            # 합쳐진 데이터를 결과 파일에 쓰기
            soundfile.write(outfile, data, samplerate)
        except:
            # handle error
            pass
    
       finally:
           # 처리가 끝나면 chunk 파일 삭제
           os.remove(file_path_chunk)