Cannot read from camera

Hi everyone,
I’m using below enviroment to build a python object detection using stream from camera.
python: 3.12
opencv-python: 4.9.0.80
ultralytics: 8.1.24
camera: laptop camera/usb HD microsft camera
OS: windows 11 Version22H2

Below is my code:

from ultralytics import YOLO
import cv2
import time

cap = cv2.VideoCapture(0)
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('output.avi', cv2.VideoWriter.fourcc('M','J','P','G'), 10, (frame_width, frame_height))


model = YOLO('yolov8x.pt')
#results = model('images/1.jpg',show=True)

while True:
    success, frame = cap.read()

    if success:
        out.write(frame)
        cv2.imshow("frame", frame)
        if cv2.waitKey(1) & 0xFF == ord('1'):
            break
    else:
        break

# Release everything when job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

I have this error: [ WARN:0@12.680] global cap_msmf.cpp:1768 CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638

I tried couple of things to resolve the issue:
1- change source from in-built camera to external usb camera, hence i changed cv2.VideoCapture(0) to cv2.VideoCapture(1) but same issue
2- i tried to modify the show by changing cv2.VideoCapture(0) to cv2.VideoCapture(0, cv2.CAP_DSHOW) , the camera window opened but i cannot see anything on this windows (almost black windows)

Please help.