The task of rapidly identifying patients infected with Mycobacterium tuberculosis (MTB) in resource-constrained environments remains a challenge. A sensitive and robust platform that does not require bacterial isolation or culture is critical in making informed diagnostic and therapeutic decisions. Here we introduce a platform for the detection of nucleic acids based on a magnetic barcoding strategy. PCR-amplified mycobacterial genes are sequence-specifically captured on microspheres, labeled by magnetic nanoprobes, and detected by nuclear magnetic resonance. All components are integrated into a single, small fluidic cartridge for streamlined on-chip operation. We use this platform to detect MTB and identify drug-resistance strains from mechanically processed sputum samples within 2.5 hours. The specificity of the assay is confirmed by a panel of clinically relevant non-MTB bacteria, and the clinical utility is demonstrated by the measurements in MTB-positive patient specimens. Combined with portable systems, the magnetic barcode assay holds promise to become a sensitive, high-throughput, and low-cost platform for point-of-care diagnostics.