This gist demonstrates fast BAM slicing without re-compressing the alignment data. It only works for BAMs generated by samtools-0.1.8+ and htslib, as it requires the BAM to be block aligned.
To use this gist, you need to first acquire and compile htslib. After that:
cd htslib; gcc -g -O2 -Wall -o fsi -I. /path/to/fsi.c libhts.a -lz
./fsi aln.bam > aln.fsi
perl fsi-get.pl aln.bam aln.fsi chr11:1000000-1200000 > slice.bam
If your BAM is not compatible with this gist (which will lead to a segfault), you need to recode the BAM with
samtools view -b ori.bam > recode.bam
FSI index format:
N n_contigs n_blocks
L contig_length
I file_offset accumulative_align_start_position genomic_span n_alignments n_bytes