Search in sources :

Example 56 with Media

use of com.ichi2.libanki.Media in project AnkiChinaAndroid by ankichinateam.

the class ZipFile method exportVerbatim.

private JSONObject exportVerbatim(ZipFile z, Context context) throws IOException {
    // close our deck & write it into the zip file, and reopen
    mCount = mCol.cardCount();
    mCol.close();
    if (!_v2sched) {
        z.write(mCol.getPath(), CollectionHelper.COLLECTION_FILENAME);
    } else {
        _addDummyCollection(z, context);
        z.write(mCol.getPath(), "collection.anki21");
    }
    mCol.reopen();
    // copy all media
    if (!mIncludeMedia) {
        return new JSONObject();
    }
    File mdir = new File(mCol.getMedia().dir());
    if (mdir.exists() && mdir.isDirectory()) {
        File[] mediaFiles = mdir.listFiles();
        return _exportMedia(z, mediaFiles, ValidateFiles.SKIP_VALIDATION);
    } else {
        return new JSONObject();
    }
}
Also used : JSONObject(com.ichi2.utils.JSONObject) File(java.io.File)

Example 57 with Media

use of com.ichi2.libanki.Media in project AnkiChinaAndroid by ankichinateam.

the class Sound method playSoundInternal.

/**
 * Plays a sound without ensuring that the playAllListener will release the audio
 */
// audio API deprecation tracked on github as #5022
@SuppressWarnings({ "PMD.EmptyIfStmt", "PMD.CollapsibleIfStatements", "deprecation" })
private void playSoundInternal(String soundPath, OnCompletionListener playAllListener, VideoView videoView) {
    Timber.d("Playing %s has listener? %b", soundPath, playAllListener != null);
    Uri soundUri = Uri.parse(soundPath);
    if ("tts".equals(soundPath.substring(0, 3))) {
    // TODO: give information about did
    // ReadText.textToSpeech(soundPath.substring(4, soundPath.length()),
    // Integer.parseInt(soundPath.substring(3, 4)));
    } else {
        // Check if the file extension is that of a known video format
        final String extension = soundPath.substring(soundPath.lastIndexOf(".") + 1).toLowerCase();
        boolean isVideo = Arrays.asList(VIDEO_WHITELIST).contains(extension);
        if (!isVideo) {
            final String guessedType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            isVideo = (guessedType != null) && guessedType.startsWith("video/");
        }
        // Also check that there is a video thumbnail, as some formats like mp4 can be audio only
        isVideo = isVideo && ThumbnailUtils.createVideoThumbnail(soundUri.getPath(), MediaStore.Images.Thumbnails.MINI_KIND) != null;
        // holder
        if (isVideo && videoView == null && mCallingActivity != null && mCallingActivity.get() != null) {
            Timber.d("Requesting AbstractFlashcardViewer play video - no SurfaceHolder");
            mPlayAllListener = playAllListener;
            ((AbstractFlashcardViewer) mCallingActivity.get()).playVideo(soundPath);
            return;
        }
        // Play media
        try {
            // Create media player
            if (mMediaPlayer == null) {
                Timber.d("Creating media player for playback");
                mMediaPlayer = new MediaPlayer();
            } else {
                Timber.d("Resetting media for playback");
                mMediaPlayer.reset();
            }
            if (mAudioManager == null) {
                mAudioManager = (AudioManager) AnkiDroidApp.getInstance().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            }
            // Provide a VideoView to the MediaPlayer if valid video file
            if (isVideo && videoView != null) {
                mMediaPlayer.setDisplay(videoView.getHolder());
                mMediaPlayer.setOnVideoSizeChangedListener((mp, width, height) -> configureVideo(videoView, width, height));
            }
            mMediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Timber.w("Media Error: (%d, %d). Calling OnCompletionListener", what, extra);
                return false;
            });
            // Setup the MediaPlayer
            mMediaPlayer.setDataSource(AnkiDroidApp.getInstance().getApplicationContext(), soundUri);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnPreparedListener(mp -> {
                Timber.d("Starting media player");
                mMediaPlayer.start();
            });
            if (playAllListener != null) {
                mMediaPlayer.setOnCompletionListener(playAllListener);
            }
            mMediaPlayer.prepareAsync();
            Timber.d("Requesting audio focus");
            mAudioManager.requestAudioFocus(afChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
        } catch (Exception e) {
            Timber.e(e, "playSounds - Error reproducing sound %s", soundPath);
            releaseSound();
        }
    }
}
Also used : AbstractFlashcardViewer(com.ichi2.anki.AbstractFlashcardViewer) Uri(android.net.Uri) MediaPlayer(android.media.MediaPlayer)

Example 58 with Media

use of com.ichi2.libanki.Media in project AnkiChinaAndroid by ankichinateam.

the class AnkiPackageExporterTest method missingFileInDeckExportDoesSkipsFile.

@Test
public void missingFileInDeckExportDoesSkipsFile() throws IOException, ImportExportException {
    // arrange
    File mediaFilePath = addTempFileToMediaAndNote();
    if (!mediaFilePath.delete()) {
        throw new IllegalStateException("need to delete temp file for test to pass");
    }
    AnkiPackageExporter exporter = getExporterForDeckWithMedia();
    Path tempExportDir = Files.createTempDirectory("AnkiDroid-missingFileInExportDoesNotThrowException-export");
    File exportedFile = new File(tempExportDir.toFile(), "export.apkg");
    // act
    exporter.exportInto(exportedFile.getAbsolutePath(), getTargetContext());
    // assert
    Path unzipDirectory = unzipFilesTo(tempExportDir, exportedFile);
    File[] files = unzipDirectory.toFile().listFiles();
    // confirm the files
    List<String> fileNames = Arrays.stream(files).map(File::getName).collect(Collectors.toList());
    assertThat(fileNames, containsInAnyOrder("collection.anki2", "media"));
    assertThat("Only two files should exist", fileNames, hasSize(2));
    checkMediaExportStringIs(files, "{}");
}
Also used : Path(java.nio.file.Path) File(java.io.File) RobolectricTest(com.ichi2.anki.RobolectricTest) Test(org.junit.Test)

Example 59 with Media

use of com.ichi2.libanki.Media in project AnkiChinaAndroid by ankichinateam.

the class AnkiPackageExporterTest method fileInExportIsCopied.

@Test
public void fileInExportIsCopied() throws IOException, ImportExportException {
    // arrange
    File tempFileInCollection = addTempFileToMediaAndNote();
    AnkiPackageExporter exporter = getExporterForDeckWithMedia();
    Path tempExportDir = Files.createTempDirectory("AnkiDroid-missingFileInExportDoesNotThrowException-export");
    File exportedFile = new File(tempExportDir.toFile(), "export.apkg");
    // act
    exporter.exportInto(exportedFile.getAbsolutePath(), getTargetContext());
    // assert
    Path unzipDirectory = unzipFilesTo(tempExportDir, exportedFile);
    File[] files = unzipDirectory.toFile().listFiles();
    // confirm the files
    List<String> fileNames = Arrays.stream(files).map(File::getName).collect(Collectors.toList());
    assertThat(fileNames, containsInAnyOrder("collection.anki2", "media", "0"));
    assertThat("Three files should exist", fileNames, hasSize(3));
    // {"0":"filename.txt"}
    String expected = String.format("{\"0\":\"%s\"}", tempFileInCollection.getName());
    checkMediaExportStringIs(files, expected);
}
Also used : Path(java.nio.file.Path) File(java.io.File) RobolectricTest(com.ichi2.anki.RobolectricTest) Test(org.junit.Test)

Example 60 with Media

use of com.ichi2.libanki.Media in project AnkiChinaAndroid by ankichinateam.

the class CollectionTest method test_furigana.

@Test
@Ignore("Pending port of media search from Rust code")
public void test_furigana() {
    Collection col = getCol();
    Models mm = col.getModels();
    Model m = mm.current();
    // filter should work
    m.getJSONArray("tmpls").getJSONObject(0).put("qfmt", "{{kana:Front}}");
    mm.save(m);
    Note n = col.newNote();
    n.setItem("Front", "foo[abc]");
    col.addNote(n);
    Card c = n.cards().get(0);
    assertTrue(c.q().endsWith("abc"));
    // and should avoid sound
    n.setItem("Front", "foo[sound:abc.mp3]");
    n.flush();
    String question = c.q(true);
    assertThat("Question «" + question + "» does not contains «anki:play».", question, containsString("anki:play"));
    // it shouldn't throw an error while people are editing
    m.getJSONArray("tmpls").getJSONObject(0).put("qfmt", "{{kana:}}");
    mm.save(m);
    c.q(true);
}
Also used : Matchers.containsString(org.hamcrest.Matchers.containsString) Ignore(org.junit.Ignore) RobolectricTest(com.ichi2.anki.RobolectricTest) Test(org.junit.Test)

Aggregations

File (java.io.File)43 IOException (java.io.IOException)26 Collection (com.ichi2.libanki.Collection)25 JSONObject (com.ichi2.utils.JSONObject)19 ArrayList (java.util.ArrayList)17 Test (org.junit.Test)17 ZipFile (java.util.zip.ZipFile)14 JSONException (com.ichi2.utils.JSONException)10 FileOutputStream (java.io.FileOutputStream)10 List (java.util.List)10 JSONArray (com.ichi2.utils.JSONArray)9 FileInputStream (java.io.FileInputStream)9 FileNotFoundException (java.io.FileNotFoundException)9 SharedPreferences (android.content.SharedPreferences)8 JSONObject (org.json.JSONObject)8 Resources (android.content.res.Resources)7 Uri (android.net.Uri)7 RobolectricTest (com.ichi2.anki.RobolectricTest)7 ConfirmModSchemaException (com.ichi2.anki.exception.ConfirmModSchemaException)7 AnkiPackageImporter (com.ichi2.libanki.importer.AnkiPackageImporter)7