Используйте фильтры adelay и amix или amerge :
ffmpeg -i main.mp3 -i secondary.mp3 -filter_complex "[1:a]adelay=20000|20000[2nd];[0:a][2nd]amix=inputs=2" out.mp3
Существует несколько проблем с Вашим кодом.
/ 5
? Ширина символов зависит от font-family
и font-size
.str
в заголовке сокр. (или иначе "сделает код недопустимым).diff
не объявляется и заканчивается в глобальной области видимостиsubstring
как предполагается, не работает как этот. Какой браузер Вы используете?hidden
не допустимое значение style.display
. Для сокрытия его, необходимо использовать значение none
но затем браузер не вычисляет offsetWidth
. Использовать style.visibility="hidden"
вместо этого.</abbr>
"Я переписал его для Вас и добавил className
таким образом, можно использовать стиль для установки font-family
и font-size
. Г-н Fooz предложил, чтобы Вы использовали наведение мыши для показа целой строки. Это не необходимо, так как современные браузеры делают это для Вас (протестированный с FF, IE, Opera и Chrome)
function fitStringToSize(str,len,className) {
var result = str; // set the result to the whole string as default
var span = document.createElement("span");
span.className=className; //Allow a classname to be set to get the right font-size.
span.style.visibility = 'hidden';
span.style.padding = '0px';
document.body.appendChild(span);
// check if the string don't fit
span.innerHTML = result;
if (span.offsetWidth > len) {
var posStart = 0, posMid, posEnd = str.length;
while (true) {
// Calculate the middle position
posMid = posStart + Math.ceil((posEnd - posStart) / 2);
// Break the loop if this is the last round
if (posMid==posEnd || posMid==posStart) break;
span.innerHTML = str.substring(0,posMid) + '…';
// Test if the width at the middle position is
// too wide (set new end) or too narrow (set new start).
if ( span.offsetWidth > len ) posEnd = posMid; else posStart=posMid;
}
//Escape
var title = str.replace("\"",""");
//Escape < and >
var body = str.substring(0,posStart).replace("<","<").replace(">",">");
result = '<abbr title="' + title + '">' + body + '…<\/abbr>';
}
document.body.removeChild(span);
return result;
}
Править: При тестировании немного больше я нашел несколько ошибок.
Я использовал Math.ceil
вместо намеченного Math.floor
(Я возлагаю ответственность, это на том английском языке не мой родной язык),
Если бы входная строка имела теги HTML затем, то результат был бы не определен (не хорошо усечь тег в середине или оставить открытые теги),
Улучшения:
<
и >
будет отображен),while
- оператор (это немного быстрее, но главная причина состояла в том, чтобы избавиться от ошибки, которая вызвала дополнительные раунды и избавиться от оператора завершения),fitStringToWidth
Версия 2:
function fitStringToWidth(str,width,className) {
// str A string where html-entities are allowed but no tags.
// width The maximum allowed width in pixels
// className A CSS class name with the desired font-name and font-size. (optional)
// ----
// _escTag is a helper to escape 'less than' and 'greater than'
function _escTag(s){ return s.replace("<","<").replace(">",">");}
//Create a span element that will be used to get the width
var span = document.createElement("span");
//Allow a classname to be set to get the right font-size.
if (className) span.className=className;
span.style.display='inline';
span.style.visibility = 'hidden';
span.style.padding = '0px';
document.body.appendChild(span);
var result = _escTag(str); // default to the whole string
span.innerHTML = result;
// Check if the string will fit in the allowed width. NOTE: if the width
// can't be determined (offsetWidth==0) the whole string will be returned.
if (span.offsetWidth > width) {
var posStart = 0, posMid, posEnd = str.length, posLength;
// Calculate (posEnd - posStart) integer division by 2 and
// assign it to posLength. Repeat until posLength is zero.
while (posLength = (posEnd - posStart) >> 1) {
posMid = posStart + posLength;
//Get the string from the beginning up to posMid;
span.innerHTML = _escTag(str.substring(0,posMid)) + '…';
// Check if the current width is too wide (set new end)
// or too narrow (set new start)
if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
}
result = '<abbr title="' +
str.replace("\"",""") + '">' +
_escTag(str.substring(0,posStart)) +
'…<\/abbr>';
}
document.body.removeChild(span);
return result;
}
На быстрый взгляд это выглядит хорошим мне. Вот некоторые незначительные предложения:
Используйте двоичный поиск для нахождения оптимального размера вместо линейного.
(дополнительно) добавьте наведение мыши так, чтобы подсказка дала бы полную строку.
Можете ли вы написать ту же функцию, но так, чтобы она соответствовала ширине и высоте div? У меня есть div с фиксированной шириной и высотой, куда мне нужно поместить текст из базы данных. если текст слишком велик для div, я хочу вырезать его и добавить рекламу ... в конце? Возможное? Спасибо
РЕДАКТИРОВАТЬ: Я нашел JS-решение для своего вопроса:
<p id="truncateMe">Lorem ipsum dolor sit amet, consectetuer adipiscing
elit. Aenean consectetuer. Etiam venenatis. Sed ultricies, pede sit
amet aliquet lobortis, nisi ante sagittis sapien, in rhoncus lectus
mauris quis massa. Integer porttitor, mi sit amet viverra faucibus,
urna libero viverra nibh, sed dictum nisi mi et diam. Nulla nunc eros,
convallis sed, varius ac, commodo et, magna. Proin vel
risus. Vestibulum eu urna. Maecenas lobortis, pede ac dictum pulvinar,
nibh ante vestibulum tortor, eget fermentum urna ipsum ac neque. Nam
urna nulla, mollis blandit, pretium id, tristique vitae, neque. Etiam
id tellus. Sed pharetra enim non nisl.</p>
<script type="text/javascript">
var len = 100;
var p = document.getElementById('truncateMe');
if (p) {
var trunc = p.innerHTML;
if (trunc.length > len) {
/* Truncate the content of the P, then go back to the end of the
previous word to ensure that we don't truncate in the middle of
a word */
trunc = trunc.substring(0, len);
trunc = trunc.replace(/\w+$/, '');
/* Add an ellipses to the end and make it a link that expands
the paragraph back to its original size */
trunc += '<a href="#" ' +
'onclick="this.parentNode.innerHTML=' +
'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
'...<\/a>';
p.innerHTML = trunc;
}
}
</script>
Для моей цели я удалил ссылку из ..., так как на моей странице есть еще одна вкладка, содержащая полный текст.