java 停止线程播放音频,在Java中单独的线程循环音频

I am making a 2d RPG game and i was wanting to get background music working. I wrote a sound class that plays the music on a separate thread but i cannot figure out how to make it loop. My Sound class is as follows:

package tileRPG.gfx;

import java.io.File;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.LineUnavailableException;

import javax.sound.sampled.SourceDataLine;

public class Sound implements Runnable

{

private String fileLocation = "res/bgMusic.wav";

public Sound() { }

public void play()

{

Thread t = new Thread(this);

t.start();

}

public void run()

{

playSound(fileLocation);

}

private void playSound(String fileName)

{

File soundFile = new File(fileName);

AudioInputStream audioInputStream = null;

try

{

audioInputStream = AudioSystem.getAudioInputStream(soundFile);

}

catch (Exception e)

{

e.printStackTrace();

}

AudioFormat audioFormat = audioInputStream.getFormat();

SourceDataLine line = null;

DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);

try

{

line = (SourceDataLine) AudioSystem.getLine(info);

line.open(audioFormat);

}

catch (LineUnavailableException e)

{

e.printStackTrace();

}

catch (Exception e)

{

e.printStackTrace();

}

line.start();

int nBytesRead = 0;

byte[] abData = new byte[128000];

while (nBytesRead != -1)

{

try

{

nBytesRead = audioInputStream.read(abData, 0, abData.length);

}

catch (IOException e)

{

e.printStackTrace();

}

if (nBytesRead >= 0)

{

int nBytesWritten = line.write(abData, 0, nBytesRead);

}

}

line.drain();

line.close();

}

}

解决方案

public void run ()

{

while(true)

{

playSound(fileLocation);

}

}

This creates an infinite loop. Adjust accordingly.

When you start a thread, it will execute any code that is in the run() method and then exit. So this is where the loop would go in order to repeatedly play the sound (without blocking your other threads/code).

This solution has no way of stopping this thread (and therefore stopping playback) with your current code, but I assume you are writing this in stages. The thread will stop playback and exit when the application does currently.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值