示例#1
0
 def test_file_frame_data(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     frames = [frame for frame in mp3.iter_frames()]
     if sys.version_info[0] >= 3:
         self.assertEqual(frames[17][22], 30)
     else:
         self.assertEqual(ord(frames[17][22]), 30)
示例#2
0
def guide(ment):

    global start_check
    start_check = False
    mp3 = Mpg123(ment)
    out = Out123()

    for frame in mp3.iter_frames(out.start):
        out.play(frame)
示例#3
0
    def read(self, filename):
        data = Mpg123(filename)

        # Get the waveform data from the mp3 file
        self.frames = list(data.iter_frames())
        # Get the metadata from the mp3 file
        self.rate, self.channels, self.encoding = data.get_format()

        return self.rate, self.channels, self.encoding
示例#4
0
def playMP3(filename):
    try:
        from mpg123 import Mpg123, Out123
        mp3 = Mpg123(filename)
        out = Out123()
        for frame in mp3.iter_frames(out.start):
            out.play(frame)
    except ValueError:
        print(ValueError)
示例#5
0
    def __init__(self, filename):
        # Load the file, if it exists and is an mp3 file
        if os.path.exists(filename) and os.path.isfile(filename):
            if filename[-3:].lower() == 'mp3':
                mp3 = Mpg123(filename)
            else:
                raise TypeError(
                        "This script can currently only handle MP3 files.")
        else:
            raise FileNotFoundError("Specified file not found.")

        # Get the waveform data from the mp3 file
        frames = list(mp3.iter_frames())
        self.frames = frames

        # Get the metadata from the mp3 file
        self.rate, self.channels, self.encoding = mp3.get_format()
示例#6
0
 def test_feeding_file(self):
     mp3 = Mpg123()
     with open('tests/bensound-scifi.mp3', 'rb') as f:
         while True:
             data = f.read(4096)
             if not data:
                 break
             mp3.feed(data)
     rate, channels, encoding = mp3.get_format()
     self.assertEqual(rate, 44100)
     self.assertEqual(channels, 2)
     self.assertEqual(encoding, 208)
     self.assertEqual(mp3.get_width_by_encoding(encoding), 2)
     self.assertEqual(encoding, mpg123.ENC_SIGNED_16)
     frame = mp3.decode_frame()
     self.assertEqual(len(frame), 188)
     frame = mp3.decode_frame()
     self.assertEqual(len(frame), 4608)
示例#7
0
 def _do_start(self, filename):
   try:
     device = alsaaudio.PCM(device=self.device)
     if filename.endswith('.wav'):
       with wave.open(filename, 'rb') as f:
         channels = f.getnchannels()
         width = f.getsampwidth()
         rate = f.getframerate()
         self._setup_device(device, channels, rate, width)
         periodsize = int(rate / 10) # 1/10th of second
         device.setperiodsize(periodsize)
         data = f.readframes(periodsize)
         chunksize = periodsize * channels * width
         while data and self.currently_playing:
           if len(data) < chunksize:
             data = data + bytearray(chunksize - len(data))
           device.write(data)
           data = f.readframes(periodsize)
     elif filename.endswith('.mp3'):
       mp3 = Mpg123(filename)
       rate, channels, encoding = mp3.get_format()
       width = mp3.get_width_by_encoding(encoding)
       self._setup_device(device, channels, rate, width)
       periodsize = int(rate / 10) # 1/10th of second
       device.setperiodsize(periodsize)
       target_chunk_size = periodsize * width * channels
       chunk = bytearray(0)
       for frames in mp3.iter_frames():
         if len(chunk) + len(frames) < target_chunk_size:
           chunk = chunk + frames
         else:
           remaining = target_chunk_size - len(chunk)
           chunk = chunk + frames[:remaining]
           device.write(chunk)
           chunk = frames[remaining:]
         if not self.currently_playing:
           break
       if len(chunk) > 0:
         remaining = target_chunk_size - len(chunk)
         chunk = chunk + bytearray(remaining)
         device.write(chunk)
   finally:
     self.currently_playing = False
     device.close()
示例#8
0
def audio_describe(codes):
    text = ''
    for code, count in codes.items():
        if code == 'thumbs_up':
            text += f'{count} users are presenting thumbs-up, '
        elif code == 'smiling':
            text += f'{count} users are smiling, '

    if text == '':
        return

    with io.BytesIO() as f:
        gTTS(text=text, lang='en', slow=False).write_to_fp(f)
        f.seek(0)
        mp3 = Mpg123()
        mp3.feed(f.read())
        out = Out123()
        for frame in mp3.iter_frames(out.start):
            out.play(frame)
示例#9
0
def playMusic(audiocard, filename):
    if checkAppStopAction():
        return
    try:
        '''
        if audiocard is None or audiocard=='':
            os.system('mpg321 "'+filename+'"') 
        else:
            os.system('mpg321 -o alsa -a '+audiocard +' "'+filename+'"') 
        '''

        mp3 = Mpg123(filename)
        out = Out123()
        for frame in mp3.iter_frames(out.start):
            out.play(frame)

        #os.system('mpg123 '+filename+'')
    except Exception as err:
        logger.error("音乐播放出现错误" + filename + ",%s", err)
示例#10
0
 def test_feeding_need_more(self):
     mp3 = Mpg123()
     mp3.feed(b'')
     with self.assertRaises(Mpg123.NeedMoreException):
         mp3.decode_frame()
示例#11
0
 def test_file_id3(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     id3 = mp3.get_id3()
     self.assertEqual(id3.artist, 'Bensound'.encode())
     self.assertEqual(id3.year, '2017'.encode())
     self.assertEqual(id3.genre, 0)
示例#12
0
 def test_file_frame(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     frame = mp3.decode_frame()
     self.assertEqual(len(frame), 188)
     frame = mp3.decode_frame()
     self.assertEqual(len(frame), 4608)
示例#13
0
 def test_file_format2(self):
     mp3 = Mpg123('tests/bensound-scifi.mp3')
     rate, channels, encoding = mp3.get_format()
     self.assertEqual(rate, 44100)
     self.assertEqual(channels, 2)
     self.assertEqual(encoding, 208)
示例#14
0
 def test_get_format_need_more(self):
     mp3 = Mpg123()
     with self.assertRaises(Mpg123.NeedMoreException):
         mp3.get_format()
示例#15
0
    periodsize = int(rate / 8)

    device.setperiodsize(periodsize)

    for frame in mp3.iter_frames():
        device.write(frame)


def usage():
    print('usage: playwav.py [-d <device>] <file>', file=sys.stderr)
    sys.exit(2)


if __name__ == '__main__':

    device = 'default'

    opts, args = getopt.getopt(sys.argv[1:], 'd:')
    for o, a in opts:
        if o == '-d':
            device = a

    if not args:
        usage()

    mp3 = Mpg123(args[0])
    device = alsaaudio.PCM(device=device)

    play(device, mp3)
示例#16
0
 def test_file_frame_length(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     self.assertEqual(mp3.frame_length(), 6835)
示例#17
0
def main():
    mp3 = Mpg123("tm.mp3")
    out = Out123()
    for frame in mp3.iter_frames(out.start):
        out.play(frame)
示例#18
0
from mpg123 import Mpg123
import wave

mp3 = Mpg123('tests/bensound-epic.mp3')
rate, channels, encoding = mp3.get_format()

wav = wave.open('bensound-epic.wav', 'wb')
wav.setnchannels(channels)
wav.setframerate(rate)
wav.setsampwidth(mp3.get_width_by_encoding(encoding))

for frame in mp3.iter_frames():
    wav.writeframes(frame)

wav.close()
示例#19
0
from mpg123 import Mpg123, Out123

### Configs ###
COIN_SOUND = 'coin'
BRICK_SOUND = 'brick'
COIN_SOUND_PATH = 'resources/mp3/coin.mp3'
BRICK_SOUND_PATH = 'resources/mp3/brick.mp3'

coin_sound = Mpg123(COIN_SOUND_PATH)
brick_sound = Mpg123(BRICK_SOUND_PATH)
sound_interface = Out123()


def play_sound(sound_type):
    ## Choice to use mpg123 os library, or pip library
    # e.g. `os.system('mpg123 -q resources/mp3/coin.mp3 &')`
    if sound_type == COIN_SOUND:
        sound = coin_sound
    elif sound_type == BRICK_SOUND:
        sound = brick_sound

        for frame in sound.iter_frames(sound_interface.start):
            sound_interface.play(frame)
示例#20
0
                else:
                    print('dislike')
                    api.like(music['id'], False, cookies)
                like_flag = window.like.like_flag

            text = mpg123.mpg123.stdout.readline()
            try:
                text = text.decode()
                if '@P 0' in text:
                    break
            except UnicodeDecodeError:
                pass


# if __name__ == '__main__':

# p = threading.Thread(target=fm163,args=(mpg123,window,director,))
if not os.path.exists('cookie'):
    login()

mpg123 = Mpg123()
director = ui.director
director.director.init(width=420, height=180, caption='bj163')
window = ui.Window(mpg123)
main_scene = ui.cocos.scene.Scene(window)

t = threading.Thread(target=fm163)
t.setDaemon(True)
t.start()
director.director.run(main_scene)
示例#21
0
    def _play(self, filename):
        try:
            device = alsaaudio.PCM(device=self.playback_device)
            if filename.endswith(".wav"):
                with wave.open(filename, "rb") as f:
                    channels = f.getnchannels()
                    width = f.getsampwidth()
                    rate = f.getframerate()
                    self._setup_device(device, channels, rate, width)
                    periodsize = rate // 10  # 1/10th of second
                    device.setperiodsize(periodsize)
                    target_chunk_size = periodsize * channels * width

                    chunk = io.BytesIO()
                    # tracking chunk length is technically useless here but we
                    # do it for consistency
                    chunk_length = 0
                    data = f.readframes(periodsize)
                    while data and self.currently_playing:
                        chunk_length += chunk.write(data)

                        if chunk_length < target_chunk_size:
                            # This (probably) is last iteration.
                            # ALSA device expects chunks of fixed period size
                            # Pad the sound with silence to complete chunk
                            chunk_length += chunk.write(
                                bytearray(target_chunk_size - chunk_length))

                        device.write(chunk.getvalue())
                        chunk.seek(0)
                        chunk_length = 0
                        data = f.readframes(periodsize)

            elif filename.endswith(".mp3"):
                mp3 = Mpg123(filename)
                rate, channels, encoding = mp3.get_format()
                width = mp3.get_width_by_encoding(encoding)
                self._setup_device(device, channels, rate, width)
                periodsize = rate // 10  # 1/10th of second
                device.setperiodsize(periodsize)
                target_chunk_size = periodsize * width * channels
                chunk = io.BytesIO()
                chunk_length = 0
                for frames in mp3.iter_frames():
                    if (chunk_length + len(frames)) <= target_chunk_size:
                        # Chunk is still smaller than what ALSA device expects
                        # (0.1 sec)
                        chunk_length += chunk.write(frames)
                    else:
                        frames_view = memoryview(frames)
                        remaining = target_chunk_size - chunk_length
                        chunk_length += chunk.write(frames_view[:remaining])
                        device.write(chunk.getvalue())
                        chunk.seek(0)
                        chunk_length = 0
                        chunk_length += chunk.write(frames_view[remaining:])

                    if not self.currently_playing:
                        break

                # ALSA device expects chunks of fixed period size
                # Pad the sound with silence to complete last chunk
                if chunk_length > 0:
                    remaining = target_chunk_size - chunk_length
                    chunk.write(bytearray(remaining))
                    device.write(chunk.getvalue())
        finally:
            self.currently_playing = False
            device.close()
示例#22
0
 def test_file_id3_song2(self):
     mp3 = Mpg123('tests/bensound-scifi.mp3')
     id3 = mp3.get_id3()
     self.assertEqual(id3.artist, 'http://www.bensound.com'.encode())
     self.assertEqual(id3.year, '2012'.encode())
     self.assertEqual(id3.genre, 1)
示例#23
0
 def test_feed_length(self):
     mp3 = Mpg123()
     with self.assertRaises(Mpg123.NeedMoreException):
         mp3.length()
示例#24
0
 def test_file_all_frames(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     frames = [frame for frame in mp3.iter_frames()]
     self.assertEqual(len(frames), 6835)
示例#25
0
def timetalk():
    hour = datetime.now().strftime("%-I")
    mp3 = Mpg123("resourses/" + hour + ".mp3")
    out = Out123()
    for frame in mp3.iter_frames(out.start):
        out.play(frame)
示例#26
0
from mpg123 import Mpg123, Out123
import asyncio
import aiohttp

mp3 = Mpg123()

out = Out123()


async def radio_streaming(mp3, out):
    async with aiohttp.ClientSession() as session:
        async with session.get(
                'http://stream.radiometal.com:8010') as response:
            while True:
                chunk = await response.content.read(4096)
                if not chunk:
                    break
                mp3.feed(chunk)
                for frame in mp3.iter_frames(out.start):
                    out.play(frame)


loop = asyncio.get_event_loop()
loop.run_until_complete(radio_streaming(mp3, out))
示例#27
0
from mpg123 import Mpg123, Out123

mp3 = Mpg123('tests/bensound-scifi.mp3')

out = Out123()

for frame in mp3.iter_frames(out.start):
    out.play(frame)
示例#28
0
 def test_file_length(self):
     mp3 = Mpg123('tests/bensound-epic.mp3')
     self.assertEqual(mp3.length(), 7872625)
示例#29
0
 def setup_mp3(self):
     self.mp3 = Mpg123(self.loc)
     self.mpgout = Out123()
     self.frames = self.mp3.iter_frames(self.mpgout.start)