簡體   English   中英

在構造函數中播放音頻而不是播放方法

[英]audio playing in constructor instead of play method

所以我一直在研究我的游戲庫,我剛剛開始研究它的聲音方面。 但問題是 Sound 從構造函數而不是 play 方法開始播放,而且停止對構造函數不起作用,只對 play 方法起作用。

我嘗試調試代碼,但沒有得到任何結果。 我也嘗試在執行 play 方法之前使用 stop 方法,但這也不起作用

下面是代碼,

import java.io.*;
import java.io.File;

import java.io.IOException;

import javax.sound.sampled.*;

// class stuff

    private Clip clip;
    private FloatControl fc;
    
    public SoundLoader(File file) {
        try {
            InputStream audioSource = new FileInputStream(file);
            InputStream bufferedInput = new BufferedInputStream(audioSource);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(bufferedInput);
            AudioFormat baseFormat = audioInputStream.getFormat();
            AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                    baseFormat.getSampleRate(),
                    baseFormat.getSampleSizeInBits(),
                    baseFormat.getChannels(),
                    baseFormat.getFrameSize(),
                    baseFormat.getFrameRate(),
                    false
                    );
            AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat, audioInputStream);
            clip = AudioSystem.getClip();
            clip.open(decodedAudioInputStream);
            fc = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void play(boolean loop){

        if(clip == null || isRunning())return;
        stop();
        while(!clip.isRunning())
            clip.start();

        if(loop)clip.loop(Clip.LOOP_CONTINUOUSLY);
            
    }

這是一個日志形式的例子,

clip starts running from constructor
same clip starts running from play method
stop method stops the clip from running from the play method
constructor keeps on playing

如果有人知道為什么會發生這種情況,那么如果您能回復此消息就好了。 謝謝

編輯:我將 clip 和 fc 更改為不是 static 因為我用 static 測試了一些東西然后我忘了把它改回正常

好的,我解決了。 這只是我在編碼時突然停電的情況,我正在項目的主要方法中播放聲音。 我很高興 Clip class 沒有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM