Room-temperature optoelectronic devices that operate at short-wavelength and mid-wavelength infrared ranges (one to eight micrometres) can be used for numerous applications1–5. To achieve the range of operating wavelengths needed for a given application, a combination of materials with different bandgaps (for example, superlattices or heterostructures)6,7 or variations in the composition of semiconductor alloys during growth8,9 are used. However, these materials are complex to fabricate, and the operating range is fixed after fabrication. Although wide-range, active and reversible tunability of the operating wavelengths in optoelectronic devices after fabrication is a highly desirable feature, no such platform has been yet developed. Here we demonstrate high-performance room-temperature infrared optoelectronics with actively variable spectra by presenting black phosphorus as an ideal candidate. Enabled by the highly strain-sensitive nature of its bandgap, which varies from 0.22 to 0.53 electronvolts, we show a continuous and reversible tuning of the operating wavelengths in light-emitting diodes and photodetectors composed of black phosphorus. Furthermore, we leverage this platform to demonstrate multiplexed nondispersive infrared gas sensing, whereby multiple gases (for example, carbon dioxide, methane and water vapour) are detected using a single light source. With its active spectral tunability while also retaining high performance, our work bridges a technological gap, presenting a potential way of meeting different requirements for emission and detection spectra in optoelectronic applications.